diff --git a/admin/functions.php b/admin/functions.php index 2b85da776..646ad5190 100644 --- a/admin/functions.php +++ b/admin/functions.php @@ -1,90 +1,92 @@ $valueJson) { $filter[$keyJson] = " "; } } //var_dump($filter);exit; echo '
'; echo ''; echo ''; echo ''; $pluginsList = array(); if (!AVideoPlugin::exists($pluginName)) { echo ""; } else { if (!empty($plugin)) { $form = jsonToFormElements($plugin, $filter); //var_dump($form); echo implode("", $form); } echo ""; } echo '
".__('Sorry you do not have the plugin')."
'; } -function jsonToFormElements($json, $filter = array()) { +function jsonToFormElements($json, $filter = array()) +{ //var_dump($json, $filter);exit; $elements = array(); foreach ($json as $keyJson => $valueJson) { if (!empty($filter) && empty($filter[$keyJson])) { continue; } $label = ""; $help = ""; if (!empty($filter[$keyJson])) { $help = "{$filter[$keyJson]}"; } $input = ""; if (is_object($valueJson)) { if ($valueJson->type === 'textarea') { $input = ""; - } else if (is_array($valueJson->type)) { + } elseif (is_array($valueJson->type)) { $input = ""; } else { //var_dump($keyJson, $valueJson); $input = ""; } $elements[] = "{$label} {$input}{$help}"; - } else if (is_bool($valueJson)) { + } elseif (is_bool($valueJson)) { $id = uniqid(); $input = '
'; $elements[] = "{$input}{$label}
{$help}"; } else { $input = ""; $elements[] = "{$label} {$input}{$help}"; } } return $elements; } -function getPluginSwitch($pluginName) { +function getPluginSwitch($pluginName) +{ if (!AVideoPlugin::exists($pluginName)) { $input = ''.__('Buy this plugin now').''; } else { $plugin = AVideoPlugin::loadPluginIfEnabled($pluginName); $pluginForced = AVideoPlugin::loadPlugin($pluginName); $id = uniqid(); $uuid = $pluginForced->getUUID(); $input = '
'; } return $input; } diff --git a/admin/general_settings_encoder.php b/admin/general_settings_encoder.php index 0a464606c..7858ef4bf 100644 --- a/admin/general_settings_encoder.php +++ b/admin/general_settings_encoder.php @@ -1,10 +1,11 @@ __('Let the encoder network (If configured) choose what is the best encoder to use'), 'doNotShowEncoderResolutionLow' => __('Do not allow encode in Low resolution'), 'doNotShowEncoderResolutionSD' => __('Do not allow encode in SD resolution'), 'doNotShowEncoderResolutionHD' => __('Do not allow encode in HD resolution'), 'makeVideosInactiveAfterEncode' => __('Maybe you need to approve or check something on your video before make it public'), - 'makeVideosUnlistedAfterEncode' => __('Maybe you need to approve or check something on your video before make it public')); + 'makeVideosUnlistedAfterEncode' => __('Maybe you need to approve or check something on your video before make it public') +); + createTable("CustomizeAdvanced", $filter); diff --git a/admin/general_settings_upload.php b/admin/general_settings_upload.php index 2f6dccc8c..e773f604d 100644 --- a/admin/general_settings_upload.php +++ b/admin/general_settings_upload.php @@ -1,9 +1,10 @@ 'The Encoder Network URL ', - 'useEncoderNetworkRecomendation'=>__('Let the encoder network (if configured) choose what is the best encoder to use'), - 'doNotShowUploadMP4Button'=>__('Users will not be able to directly upload, only use the encoder'), - 'doNotShowImportMP4Button'=>__('Disable the option to import MP4 videos from your local (Server) storage'), - 'doNotShowEncoderButton'=>__('Do not show the button to the encoder'), - 'doNotShowEmbedButton'=>__('Check this if you will not use embed videos on your site')); + 'encoderNetwork'=>'The Encoder Network URL ', + 'useEncoderNetworkRecomendation'=>__('Let the encoder network (if configured) choose what is the best encoder to use'), + 'doNotShowUploadMP4Button'=>__('Users will not be able to directly upload, only use the encoder'), + 'doNotShowImportMP4Button'=>__('Disable the option to import MP4 videos from your local (Server) storage'), + 'doNotShowEncoderButton'=>__('Do not show the button to the encoder'), + 'doNotShowEmbedButton'=>__('Check this if you will not use embed videos on your site') +); createTable("CustomizeAdvanced", $filter); diff --git a/admin/general_settings_user.php b/admin/general_settings_user.php index 9cf3eb760..8fdf24d0e 100644 --- a/admin/general_settings_user.php +++ b/admin/general_settings_user.php @@ -1,14 +1,15 @@ __('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), - 'disableNativeSignIn'=>__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), - 'disablePersonalInfo'=>__('Disable the My Account personal info like: First and Last Name and address'), - 'newUsersCanStream'=>__('Automatic allow new users to use your Livestream Platform'), - 'doNotIndentifyByEmail'=>__('Do not show user\'s email on the site'), - 'doNotIndentifyByName'=>__('Do not show user\'s name on the site'), - 'doNotIndentifyByUserName'=>__('Do not show user\'s username on the site'), - 'unverifiedEmailsCanNOTLogin'=>__('Users must verify their emails before login'), - 'onlyVerifiedEmailCanUpload'=>__('Users must verify their emails before upload/submit videos'), - 'sendVerificationMailAutomaic'=>__('After sign up we will automatic send a verification email'), - 'userMustBeLoggedIn'=>__('Hide the website to non logged users')); +$filter = array( + 'disableNativeSignUp'=>__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), + 'disableNativeSignIn'=>__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), + 'disablePersonalInfo'=>__('Disable the My Account personal info like: First and Last Name and address'), + 'newUsersCanStream'=>__('Automatic allow new users to use your Livestream Platform'), + 'doNotIndentifyByEmail'=>__('Do not show user\'s email on the site'), + 'doNotIndentifyByName'=>__('Do not show user\'s name on the site'), + 'doNotIndentifyByUserName'=>__('Do not show user\'s username on the site'), + 'unverifiedEmailsCanNOTLogin'=>__('Users must verify their emails before login'), + 'onlyVerifiedEmailCanUpload'=>__('Users must verify their emails before upload/submit videos'), + 'sendVerificationMailAutomaic'=>__('After sign up we will automatic send a verification email'), + 'userMustBeLoggedIn'=>__('Hide the website to non logged users') +); createTable("CustomizeUser", $filter); diff --git a/objects/Channel.php b/objects/Channel.php index 19945472f..e28e4d006 100644 --- a/objects/Channel.php +++ b/objects/Channel.php @@ -1,61 +1,55 @@ 0 "; - if($activeOnly){ + if ($activeOnly) { $sql .= " AND u.status = 'a' "; } $sql .= BootGrid::getSqlFromPost(array('user', 'about', 'channelName', 'u.name', 'u.email'), "", "", false, $FIND_IN_SET); - - $res = sqlDAL::readSql($sql); + + $res = sqlDAL::readSql($sql); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $subscribe = array(); - if ($res!=false) { + if ($res != false) { foreach ($fullResult as $row) { unset($row['password']); $subscribe[] = $row; } } else { $subscribe = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $subscribe; } - - - static function getTotalChannels($activeOnly=true){ + + + public static function getTotalChannels($activeOnly=true) + { global $global; $sql = "SELECT count(*) as total " . " FROM users u " . " WHERE (SELECT count(v.id) FROM videos v where v.users_id = u.id) > 0 "; - if($activeOnly){ + if ($activeOnly) { $sql .= " AND u.status = 'a' "; } $sql .= BootGrid::getSqlFromPost(array('user', 'about')); - $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); - if ($res) { - $row = intval($data['total']); - } else { - $row = 0; - } - return $row; + return $res ? intval($data['total']) : 0; } - } - diff --git a/objects/Object.php b/objects/Object.php index eee2cd63d..502f526a3 100644 --- a/objects/Object.php +++ b/objects/Object.php @@ -1,533 +1,564 @@ load($id); } } - protected function load($id) { + protected function load($id) + { $row = self::getFromDb($id); - if (empty($row)) + if (empty($row)) { return false; + } foreach ($row as $key => $value) { $this->$key = $value; } return true; } - static function getNowFromDB() { + public static function getNowFromDB() + { global $global; $sql = "SELECT NOW() as my_date_field"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } - static function setTimeZone() { + public static function setTimeZone() + { global $advancedCustom; $row = self::getNowFromDB(); $dt = new DateTime($row['my_date_field']); $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type); - if(empty($timeZOnesOptions[$advancedCustom->timeZone->value])){ + if (empty($timeZOnesOptions[$advancedCustom->timeZone->value])) { return false; } try { $objDate = new DateTimeZone($timeZOnesOptions[$advancedCustom->timeZone->value]); - if(is_object($objDate)){ + if (is_object($objDate)) { $dt->setTimezone($objDate); date_default_timezone_set($timeZOnesOptions[$advancedCustom->timeZone->value]); return $dt; } return false; } catch (Exception $exc) { _error_log("setTimeZone: ".$exc->getMessage(), AVideoLog::$ERROR); return false; } } - static protected function getFromDb($id) { + protected static function getFromDb($id) + { global $global; $id = intval($id); $sql = "SELECT * FROM " . static::getTableName() . " WHERE id = ? LIMIT 1"; // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about $res = sqlDAL::readSql($sql, "i", array($id), true); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } - static function getAll() { + public static function getAll() + { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - static function getTotal() { + public static function getTotal() + { //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; if (!static::isTableInstalled()) { return 0; } $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; $sql .= self::getSqlSearchFromPost(); $res = sqlDAL::readSql($sql); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); return $countRow; } - static function getSqlFromPost($keyPrefix = "") { + public static function getSqlFromPost($keyPrefix = "") + { global $global; $sql = self::getSqlSearchFromPost(); if (empty($_POST['sort']) && !empty($_GET['order'][0]['dir'])) { $index = intval($_GET['order'][0]['column']); $_GET['columns'][$index]['data']; $_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir']; } - // add a security here + // add a security here if (!empty($_POST['sort'])) { foreach ($_POST['sort'] as $key => $value) { $_POST['sort'][xss_esc($key)] = xss_esc($value); } } if (!empty($_POST['sort'])) { $orderBy = array(); foreach ($_POST['sort'] as $key => $value) { $key = $global['mysqli']->real_escape_string($key); //$value = $global['mysqli']->real_escape_string($value); $direction = "ASC"; if (strtoupper($value) === "DESC") { $direction = "DESC"; } $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); $orderBy[] = " {$keyPrefix}{$key} {$value} "; } $sql .= " ORDER BY " . implode(",", $orderBy); } $sql .= self::getSqlLimit(); return $sql; } - static function getSqlLimit() { + public static function getSqlLimit() + { global $global; $sql = ""; if (empty($_POST['rowCount']) && !empty($_GET['length'])) { $_POST['rowCount'] = intval($_GET['length']); } if (empty($_POST['current']) && !empty($_GET['start'])) { $_POST['current'] = ($_GET['start'] / $_GET['length']) + 1; - } else if (empty($_POST['current']) && isset($_GET['start'])) { + } elseif (empty($_POST['current']) && isset($_GET['start'])) { $_POST['current'] = 1; } $_POST['current'] = getCurrentPage(); $_POST['rowCount'] = getRowCount(); if (!empty($_POST['rowCount']) && !empty($_POST['current']) && $_POST['rowCount'] > 0) { $_POST['rowCount'] = intval($_POST['rowCount']); $_POST['current'] = intval($_POST['current']); $current = ($_POST['current'] - 1) * $_POST['rowCount']; $current = $current < 0 ? 0 : $current; $sql .= " LIMIT $current, {$_POST['rowCount']} "; } else { $_POST['current'] = 0; $_POST['rowCount'] = 0; $sql .= " LIMIT 1000 "; } return $sql; } - static function getSqlSearchFromPost() { + public static function getSqlSearchFromPost() + { $sql = ""; if (!empty($_POST['searchPhrase'])) { $_GET['q'] = $_POST['searchPhrase']; - } else if (!empty($_GET['search']['value'])) { + } elseif (!empty($_GET['search']['value'])) { $_GET['q'] = $_GET['search']['value']; } if (!empty($_GET['q'])) { global $global; $search = $global['mysqli']->real_escape_string(xss_esc($_GET['q'])); $like = array(); $searchFields = static::getSearchFieldsNames(); foreach ($searchFields as $value) { $like[] = " {$value} LIKE '%{$search}%' "; // for accent insensitive $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; } if (!empty($like)) { $sql .= " AND (" . implode(" OR ", $like) . ")"; } else { $sql .= " AND 1=1 "; } } return $sql; } - function save() { + public function save() + { if (!$this->tableExists()) { _error_log("Save error, table " . static::getTableName() . " does not exists", AVideoLog::$ERROR); return false; } global $global; $fieldsName = $this->getAllFields(); if (!empty($this->id)) { $sql = "UPDATE " . static::getTableName() . " SET "; $fields = array(); foreach ($fieldsName as $value) { if (strtolower($value) == 'created') { // do nothing } elseif (strtolower($value) == 'modified') { $fields[] = " {$value} = now() "; - } else if (is_numeric($this->$value)) { + } elseif (is_numeric($this->$value)) { $fields[] = " `{$value}` = {$this->$value} "; - } else if (strtolower($this->$value) == 'null') { + } elseif (strtolower($this->$value) == 'null') { $fields[] = " `{$value}` = NULL "; } else { $fields[] = " `{$value}` = '{$this->$value}' "; } } $sql .= implode(", ", $fields); $sql .= " WHERE id = {$this->id}"; } else { $sql = "INSERT INTO " . static::getTableName() . " ( "; $sql .= "`" . implode("`,`", $fieldsName) . "` )"; $fields = array(); foreach ($fieldsName as $value) { if (strtolower($value) == 'created' || strtolower($value) == 'modified') { $fields[] = " now() "; } elseif (!isset($this->$value) || strtolower($this->$value) == 'null') { $fields[] = " NULL "; } else { $fields[] = " '{$this->$value}' "; } } $sql .= " VALUES (" . implode(", ", $fields) . ")"; } //if(static::getTableName() == 'subscriptions') echo $sql; $insert_row = sqlDAL::writeSql($sql); if ($insert_row) { if (empty($this->id)) { $id = $global['mysqli']->insert_id; } else { $id = $this->id; } return $id; } else { _error_log("ObjectYPT::save Error on save: " . $sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error, AVideoLog::$ERROR); return false; } } - private function getAllFields() { + private function getAllFields() + { global $global, $mysqlDatabase; $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '" . static::getTableName() . "'"; $res = sqlDAL::readSql($sql, "s", array($mysqlDatabase)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row["COLUMN_NAME"]; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - function delete() { + public function delete() + { global $global; if (!empty($this->id)) { $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($this->id)); } _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); return false; } - static function setCache($name, $value) { + public static function setCache($name, $value) + { $cachefile = self::getCacheFileName($name); make_path($cachefile); $bytes = @file_put_contents($cachefile, json_encode($value)); self::setSessionCache($name, $value); return $bytes; } - static function cleanCacheName($name) { + public static function cleanCacheName($name) + { $name = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $name); $name = preg_replace('/[!#$&\'()*+,:;=?@[\\]% -]+/', '_', trim(strtolower(cleanString($name)))); $name = preg_replace('/\/{2,}/', '/', trim(strtolower(cleanString($name)))); return preg_replace('/[\x00-\x1F\x7F]/u', '', $name); } /** - * + * * @param type $name * @param type $lifetime, if is = 0 it is unlimited * @return type */ - static function getCache($name, $lifetime = 60, $ignoreSessionCache=false) { - if(isCommandLineInterface()){ + public static function getCache($name, $lifetime = 60, $ignoreSessionCache=false) + { + if (isCommandLineInterface()) { return false; } global $getCachesProcessed, $_getCache; - - if(empty($_getCache)){ + + if (empty($_getCache)) { $_getCache = array(); } - - if(empty($getCachesProcessed)){ + + if (empty($getCachesProcessed)) { $getCachesProcessed=array(); } $cachefile = self::getCacheFileName($name); - - if(!empty($_getCache[$name])){ + + if (!empty($_getCache[$name])) { return $_getCache[$name]; } - - if(empty($getCachesProcessed[$name])){ + + if (empty($getCachesProcessed[$name])) { $getCachesProcessed[$name] = 0; } - $getCachesProcessed[$name]++; - + $getCachesProcessed[$name]++; + if (!empty($_GET['lifetime'])) { $lifetime = intval($_GET['lifetime']); } - + if (!empty($ignoreSessionCache)) { $session = self::getSessionCache($name, $lifetime); if (!empty($session)) { $_getCache[$name] = $session; return $session; } } if (file_exists($cachefile) && (empty($lifetime) || time() - $lifetime <= filemtime($cachefile))) { $c = @url_get_contents($cachefile); $json = json_decode($c); self::setSessionCache($name, $json); $_getCache[$name] = $json; return $json; - } else if (file_exists($cachefile)) { + } elseif (file_exists($cachefile)) { self::deleteCache($name); } } - static function deleteCache($name) { + public static function deleteCache($name) + { $cachefile = self::getCacheFileName($name); @unlink($cachefile); self::deleteSessionCache($name); ObjectYPT::deleteCacheFromPattern($name); } - static function deleteALLCache() { + public static function deleteALLCache() + { $tmpDir = self::getCacheDir(); rrmdir($tmpDir); self::deleteAllSessionCache(); self::setLastDeleteALLCacheTime(); } - static function getCacheDir() { + public static function getCacheDir() + { $tmpDir = getTmpDir(); $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/"; $tmpDir .= "YPTObjectCache" . "/"; if (class_exists("User_Location")) { $loc = User_Location::getThisUserLocation(); if (!empty($loc) && !empty($loc['country_code'])) { $tmpDir .= $loc['country_code'] . "/"; } } make_path($tmpDir); if (!file_exists($tmpDir . "index.html")) {// to avoid search into the directory file_put_contents($tmpDir . "index.html", time()); } return $tmpDir; } - static function getCacheFileName($name) { + public static function getCacheFileName($name) + { $name = self::cleanCacheName($name); $tmpDir = self::getCacheDir(); $uniqueHash = md5(__FILE__); return $tmpDir . DIRECTORY_SEPARATOR . $name . $uniqueHash; } - static function deleteCacheFromPattern($name) { + public static function deleteCacheFromPattern($name) + { $name = self::cleanCacheName($name); $tmpDir = self::getCacheDir(); $filePattern = $tmpDir . DIRECTORY_SEPARATOR . $name; foreach (glob("{$filePattern}*") as $filename) { unlink($filename); } self::deleteSessionCache($name); } /** * Make sure you start the session before any output * @param type $name * @param type $value */ - static function setSessionCache($name, $value) { + public static function setSessionCache($name, $value) + { $name = self::cleanCacheName($name); _session_start(); $_SESSION['user']['sessionCache'][$name]['value'] = json_encode($value); $_SESSION['user']['sessionCache'][$name]['time'] = time(); - if(empty($_SESSION['user']['sessionCache']['time'])){ + if (empty($_SESSION['user']['sessionCache']['time'])) { $_SESSION['user']['sessionCache']['time'] = time(); } } /** - * + * * @param type $name * @param type $lifetime, if is = 0 it is unlimited * @return type */ - static function getSessionCache($name, $lifetime = 60) { + public static function getSessionCache($name, $lifetime = 60) + { $name = self::cleanCacheName($name); if (!empty($_GET['lifetime'])) { $lifetime = intval($_GET['lifetime']); } if (!empty($_SESSION['user']['sessionCache'][$name])) { if ((empty($lifetime) || time() - $lifetime <= $_SESSION['user']['sessionCache'][$name]['time'])) { $c = $_SESSION['user']['sessionCache'][$name]['value']; return json_decode($c); } _session_start(); unset($_SESSION['user']['sessionCache'][$name]); } return null; } - - - static function clearSessionCache() { + + public static function clearSessionCache() + { unset($_SESSION['user']['sessionCache']); } - static private function getLastDeleteALLCacheTimeFile() { + private static function getLastDeleteALLCacheTimeFile() + { $tmpDir = getTmpDir(); $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/"; $tmpDir .= "lastDeleteALLCacheTime.cache"; return $tmpDir; } - static function setLastDeleteALLCacheTime() { + public static function setLastDeleteALLCacheTime() + { $file = self::getLastDeleteALLCacheTimeFile(); _error_log("ObjectYPT::setLastDeleteALLCacheTime {$file}"); return file_put_contents($file, time()); } - static function getLastDeleteALLCacheTime() { + public static function getLastDeleteALLCacheTime() + { global $getLastDeleteALLCacheTime; - if(empty($getLastDeleteALLCacheTime)){ + if (empty($getLastDeleteALLCacheTime)) { $getLastDeleteALLCacheTime = (int) @file_get_contents(self::getLastDeleteALLCacheTimeFile(), time()); } return $getLastDeleteALLCacheTime; } - static function checkSessionCacheBasedOnLastDeleteALLCacheTime() { + public static function checkSessionCacheBasedOnLastDeleteALLCacheTime() + { /* var_dump( - $session_var['time'], - self::getLastDeleteALLCacheTime(), - humanTiming($session_var['time']), - humanTiming(self::getLastDeleteALLCacheTime()), + $session_var['time'], + self::getLastDeleteALLCacheTime(), + humanTiming($session_var['time']), + humanTiming(self::getLastDeleteALLCacheTime()), $session_var['time'] <= self::getLastDeleteALLCacheTime()); - * + * */ if (empty($_SESSION['user']['sessionCache']['time']) || $_SESSION['user']['sessionCache']['time'] <= self::getLastDeleteALLCacheTime()) { self::deleteAllSessionCache(); return false; } return true; } - static function deleteSessionCache($name) { + public static function deleteSessionCache($name) + { $name = self::cleanCacheName($name); _session_start(); $_SESSION['user']['sessionCache'][$name] = null; unset($_SESSION['user']['sessionCache'][$name]); } - static function deleteAllSessionCache() { + public static function deleteAllSessionCache() + { _session_start(); unset($_SESSION['user']['sessionCache']); } - function tableExists() { + public function tableExists() + { return self::isTableInstalled(); } - static function isTableInstalled($tableName = "") { + public static function isTableInstalled($tableName = "") + { global $global, $tableExists; if (empty($tableName)) { $tableName = static::getTableName(); } if (!isset($tableExists[$tableName])) { $res = sqlDAL::readSql("SHOW TABLES LIKE '" . $tableName . "'"); $result = sqlDal::num_rows($res); sqlDAL::close($res); $tableExists[$tableName] = !empty($result); } return $tableExists[$tableName]; } - } //abstract class Object extends ObjectYPT{}; diff --git a/objects/aVideoEncoder.json.php b/objects/aVideoEncoder.json.php index a4518516c..aeaf0767d 100644 --- a/objects/aVideoEncoder.json.php +++ b/objects/aVideoEncoder.json.php @@ -1,209 +1,207 @@ error = true; global $global, $config; if (!isset($global['systemRootPath'])) { require_once '../videos/configuration.php'; } require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; if (empty($_POST)) { $obj->msg = __("Your POST data is empty may be your vide file is too big for the host"); _error_log($obj->msg); die(json_encode($obj)); } _error_log("aVideoEncoder.json: start"); if (empty($_POST['format']) || !in_array($_POST['format'], $global['allowedExtension'])) { _error_log("aVideoEncoder.json: Extension not allowed File " . __FILE__ . ": " . json_encode($_POST)); die(); } // pass admin user and pass $user = new User("", @$_POST['user'], @$_POST['password']); $user->login(false, true); if (!User::canUpload()) { _error_log("aVideoEncoder.json: Permission denied to receive a file: " . json_encode($_POST)); $obj->msg = __("Permission denied to receive a file: " . json_encode($_POST)); _error_log($obj->msg); die(json_encode($obj)); } if (!empty($_POST['videos_id']) && !Video::canEdit($_POST['videos_id'])) { _error_log("aVideoEncoder.json: Permission denied to edit a video: " . json_encode($_POST)); $obj->msg = __("Permission denied to edit a video: " . json_encode($_POST)); _error_log($obj->msg); die(json_encode($obj)); } _error_log("aVideoEncoder.json: start to receive: " . json_encode($_POST)); // check if there is en video id if yes update if is not create a new one $video = new Video("", "", @$_POST['videos_id']); $obj->video_id = @$_POST['videos_id']; $title = $video->getTitle(); $description = $video->getDescription(); if (empty($title) && !empty($_POST['title'])) { $title = $video->setTitle($_POST['title']); } elseif (empty($title)) { $video->setTitle("Automatic Title"); } if (empty($description)) { $video->setDescription($_POST['description']); } $video->setDuration($_POST['duration']); $status = $video->getStatus(); // if status is not unlisted if ($status !== 'u' && $status !== 'a') { if (empty($advancedCustom->makeVideosInactiveAfterEncode)) { // set active $video->setStatus('a'); - } else if (empty($advancedCustom->makeVideosUnlistedAfterEncode)) { + } elseif (empty($advancedCustom->makeVideosUnlistedAfterEncode)) { // set active $video->setStatus('u'); } else { $video->setStatus('i'); } } $video->setVideoDownloadedLink($_POST['videoDownloadedLink']); _error_log("aVideoEncoder.json: Encoder receiving post " . json_encode($_POST)); //_error_log(print_r($_POST, true)); if (preg_match("/(mp3|wav|ogg)$/i", $_POST['format'])) { $type = 'audio'; $video->setType($type); } elseif (preg_match("/(mp4|webm|zip)$/i", $_POST['format'])) { $type = 'video'; $video->setType($type); } $videoFileName = $video->getFilename(); if (empty($videoFileName)) { $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($title)); $videoFileName = uniqid($mainName . "_YPTuniqid_", true); $video->setFilename($videoFileName); } - $destination_local = "{$global['systemRootPath']}videos/{$videoFileName}"; if (!empty($_FILES)) { _error_log("aVideoEncoder.json: Files " . json_encode($_FILES)); } else { _error_log("aVideoEncoder.json: Files EMPTY"); if (!empty($_REQUEST['downloadURL'])) { $_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_REQUEST['downloadURL']); - if(empty($_FILES['video']['tmp_name'])){ + if (empty($_FILES['video']['tmp_name'])) { _error_log("aVideoEncoder.json: ******** Download ERROR " . $_REQUEST['downloadURL']); } } } if (!empty($_FILES['video']['error'])) { $phpFileUploadErrors = array( 0 => 'There is no error, the file uploaded with success', 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk.', 8 => 'A PHP extension stopped the file upload.', ); _error_log("aVideoEncoder.json: ******** Files ERROR " . $phpFileUploadErrors[$_FILES['video']['error']]); if (!empty($_POST['downloadURL'])) { $_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_POST['downloadURL']); } } if (empty($_FILES['video']['tmp_name']) && !empty($_POST['chunkFile'])) { $_FILES['video']['tmp_name'] = $_POST['chunkFile']; } // get video file from encoder if (!empty($_FILES['video']['tmp_name'])) { $resolution = ""; if (!empty($_POST['resolution'])) { $resolution = "_{$_POST['resolution']}"; } $filename = "{$videoFileName}{$resolution}.{$_POST['format']}"; $fsize = filesize($_FILES['video']['tmp_name']); _error_log("aVideoEncoder.json: receiving video upload to {$filename} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")" . json_encode($_FILES)); decideMoveUploadedToVideos($_FILES['video']['tmp_name'], $filename); } else { // set encoding $video->setStatus('e'); } if (!empty($_FILES['image']['tmp_name']) && !file_exists("{$destination_local}.jpg")) { if (!move_uploaded_file($_FILES['image']['tmp_name'], "{$destination_local}.jpg")) { $obj->msg = print_r(sprintf(__("Could not move image file [%s.jpg]"), $destination_local), true); _error_log("aVideoEncoder.json: " . $obj->msg); die(json_encode($obj)); } } if (!empty($_FILES['gifimage']['tmp_name']) && !file_exists("{$destination_local}.gif")) { if (!move_uploaded_file($_FILES['gifimage']['tmp_name'], "{$destination_local}.gif")) { $obj->msg = print_r(sprintf(__("Could not move gif image file [%s.gif]"), $destination_local), true); _error_log("aVideoEncoder.json: " . $obj->msg); die(json_encode($obj)); } } if (!empty($_POST['encoderURL'])) { $video->setEncoderURL($_POST['encoderURL']); } if (!empty($_POST['categories_id'])) { $video->setCategories_id($_POST['categories_id']); } $video_id = $video->save(); $video->updateDurationIfNeed(); $video->updateHLSDurationIfNeed(); if (!empty($_POST['usergroups_id'])) { if (!is_array($_POST['usergroups_id'])) { $_POST['usergroups_id'] = array($_POST['usergroups_id']); } UserGroups::updateVideoGroups($video_id, $_POST['usergroups_id']); } $obj->error = false; $obj->video_id = $video_id; _error_log("aVideoEncoder.json: Files Received for video {$video_id}: " . $video->getTitle()); die(json_encode($obj)); /* _error_log(print_r($_POST, true)); _error_log(print_r($_FILES, true)); var_dump($_POST, $_FILES); */ -function downloadVideoFromDownloadURL($downloadURL) { +function downloadVideoFromDownloadURL($downloadURL) +{ global $global; _error_log("aVideoEncoder.json: Try to download " . $downloadURL); $file = url_get_contents($_POST['downloadURL']); - if(strlen($file)<20000){ + if (strlen($file)<20000) { //it is not a video return false; } _error_log("aVideoEncoder.json: Got the download " . $downloadURL); if ($file) { - $_FILES['video']['name'] = basename($downloadURL); - + $temp = "{$global['systemRootPath']}videos/cache/tmpFile/" . $_FILES['video']['name']; _error_log("aVideoEncoder.json: save " . $temp); make_path($temp); file_put_contents($temp, $file); return $temp; } return false; } diff --git a/objects/ajaxErrorCatcher.php b/objects/ajaxErrorCatcher.php index ffbcf6c60..b60d76a62 100644 --- a/objects/ajaxErrorCatcher.php +++ b/objects/ajaxErrorCatcher.php @@ -1,7 +1,7 @@ - diff --git a/objects/bootGrid.php b/objects/bootGrid.php index ebe6dce9f..4d5cf951a 100644 --- a/objects/bootGrid.php +++ b/objects/bootGrid.php @@ -1,78 +1,78 @@ $value) { $direction = "ASC"; if(strtoupper($value)==="DESC"){ $direction = "DESC"; } $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); if($key=='order'){ $key = '`order`'; } $orderBy[] = " {$keyPrefix}{$key} {$direction} "; } $sql .= " ORDER BY ".implode(",", $orderBy); } else { $sql .= $alternativeOrderBy; } $rowCount = getRowCount(); - $current = getCurrentPage(); + $current = getCurrentPage(); $currentP = ($current-1)*$rowCount; - + if($rowCount>0){ $sql .= " LIMIT $currentP, {$rowCount} "; } return $sql; } static function getSqlSearchFromPost($searchFieldsNames = array(), $connection = "AND") { $sql = ""; if (!empty($_GET['searchPhrase'])) { $_POST['searchPhrase'] = $_GET['searchPhrase']; } else if (!empty($_GET['search']['value'])) { $_POST['searchPhrase'] = $_GET['search']['value']; }else if (!empty($_GET['q'])) { $_POST['searchPhrase'] = $_GET['q']; } - + if(!empty($_POST['searchPhrase'])){ global $global; $search = $global['mysqli']->real_escape_string(xss_esc($_POST['searchPhrase'])); $like = array(); foreach ($searchFieldsNames as $value) { $like[] = " {$value} LIKE '%{$search}%' "; // for accent insensitive $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; } if(!empty($like)){ $sql .= " {$connection} (". implode(" OR ", $like).")"; }else{ $sql .= " {$connection} 1=1 "; } } return $sql; } } diff --git a/objects/categories.json.php b/objects/categories.json.php index c2d59bb01..d952443a8 100644 --- a/objects/categories.json.php +++ b/objects/categories.json.php @@ -1,38 +1,42 @@ ","
","
"); +$breaks = array('
', '
', '
'); foreach ($categories as $key => $value) { - $categories[$key]['iconHtml'] = ""; + $categories[$key]['iconHtml'] = ""; $categories[$key]['description'] = str_ireplace($breaks, "\r\n", $value['description']); /* $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; - $res = sqlDAL::readSql($sql,"i",array($value['id'])); + $res = sqlDAL::readSql($sql,"i",array($value['id'])); $catTypeCache = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if($catTypeCache!=false){ if($catTypeCache['manualSet']=="0"){ $categories[$key]['type'] = "3"; } else { $categories[$key]['type'] = $catTypeCache['type']; } } else { $categories[$key]['type'] = "3"; - } - * + } + * */ } -if(empty($_POST['sort']) && empty($_GET['sort'])){ +if (empty($_POST['sort']) && empty($_GET['sort'])) { array_multisort(array_column($categories, 'hierarchyAndName'), SORT_ASC, $categories); } echo '{ "current": '.$_REQUEST['current'].',"rowCount": '.$_REQUEST['rowCount'].', "total": '.$total.', "rows":'. json_encode($categories).'}'; diff --git a/objects/category.php b/objects/category.php index 6e1b8184e..9bb4d0c43 100644 --- a/objects/category.php +++ b/objects/category.php @@ -1,686 +1,686 @@ order); } function setOrder($order) { $this->order = intval($order); } function getUsers_id() { if (empty($this->users_id)) { $this->users_id = User::getId(); } return $this->users_id; } function getPrivate() { return $this->private; } function setUsers_id($users_id) { // only admin can change owner if (!empty($this->users_id) && !User::isAdmin()) { return false; } $this->users_id = intval($users_id); } function setPrivate($private) { $this->private = empty($private) ? 0 : 1; } function setName($name) { $this->name = xss_esc($name); } function setClean_name($clean_name) { $clean_name = preg_replace('/\W+/', '-', strtolower(cleanString($clean_name))); $this->clean_name = $clean_name; } function setNextVideoOrder($nextVideoOrder) { $this->nextVideoOrder = $nextVideoOrder; } function setParentId($parentId) { $this->parentId = $parentId; } /* function setType($type, $overwriteUserId = 0) { global $global; $internalId = $overwriteUserId; if (empty($internalId)) { $internalId = $this->id; } $exist = false; // require this cause of Video::autosetCategoryType - but should be moveable easy here.. require_once dirname(__FILE__) . '/../objects/video.php'; $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; $res = sqlDAL::readSql($sql, "i", array($internalId)); $catTypeCache = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($catTypeCache != false) { $exist = true; } if ($type == "3") { // auto-cat-type Video::autosetCategoryType($internalId); } else { if ($exist) { $sql = "UPDATE `category_type_cache` SET `type` = ?, `manualSet` = '1' WHERE `category_type_cache`.`categoryId` = ?;"; sqlDAL::writeSql($sql, "si", array($type, $internalId)); } else { $sql = "INSERT INTO `category_type_cache` (`categoryId`, `type`, `manualSet`) VALUES (?,?,'1')"; sqlDAL::writeSql($sql, "is", array($internalId, $type)); } } } - * + * */ function setDescription($description) { $this->description = xss_esc($description); } function __construct($id, $name = '') { if (empty($id)) { // get the category data from category and pass $this->name = xss_esc($name); } else { $this->id = $id; // get data from id $this->load($id); } } private function load($id) { $row = self::getCategory($id); if (empty($row)) return false; foreach ($row as $key => $value) { $this->$key = $value; } return true; } function loadSelfCategory() { $this->load($this->getId()); } function save($allowOfflineUser = false) { global $global; if (!$allowOfflineUser && !self::canCreateCategory()) { return false; } if (!$allowOfflineUser && !empty($this->id) && !self::userCanEditCategory($this->id)) { return false; } if (empty($this->users_id)) { $this->users_id = User::getId(); } $this->clean_name = self::fixCleanTitle($this->clean_name, 1, $this->id); // check if clean name exists $exists = $this->getCategoryByName($this->clean_name); if (!empty($exists) && $exists['id'] != $this->id) { $this->clean_name .= uniqid(); } $this->nextVideoOrder = intval($this->nextVideoOrder); $this->parentId = intval($this->parentId); if (!empty($this->id)) { $sql = "UPDATE categories SET " . "name = ?," . "clean_name = ?," . "description = ?," . "nextVideoOrder = ?," . "parentId = ?," . "iconClass = ?," . "users_id = ?," . "`private` = ?, allow_download = ?, `order` = ?, modified = now() WHERE id = ?"; $format = "sssiisiiiii"; $values = array(xss_esc($this->name), xss_esc($this->clean_name), xss_esc($this->description), $this->nextVideoOrder, $this->parentId, $this->getIconClass(), $this->getUsers_id(), $this->getPrivate(), $this->getAllow_download(), $this->getOrder(), $this->id); } else { $sql = "INSERT INTO categories ( " . "name," . "clean_name," . "description," . "nextVideoOrder," . "parentId," . "iconClass, " . "users_id, " . "`private`, allow_download, `order`, created, modified) VALUES (?, ?,?,?,?,?,?,?,?,?,now(), now())"; $format = "sssiisiiii"; $values = array(xss_esc($this->name), xss_esc($this->clean_name), xss_esc($this->description), $this->nextVideoOrder, $this->parentId, $this->getIconClass(), $this->getUsers_id(), $this->getPrivate(), $this->getAllow_download(), $this->getOrder()); } $insert_row = sqlDAL::writeSql($sql, $format, $values); if ($insert_row) { $_SESSION['getAllCategoriesClearCache'] = 1; ObjectYPT::deleteALLCache(); if (empty($this->id)) { $id = $global['mysqli']->insert_id; } else { $id = $this->id; } return $id; } else { die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } static function fixCleanTitle($clean_title, $count, $id, $original_title = "") { global $global; if (empty($original_title)) { $original_title = $clean_title; } $sql = "SELECT * FROM categories WHERE clean_name = '{$clean_title}' "; if (!empty($id)) { $sql .= " AND id != {$id} "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $cleanTitleExists = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($cleanTitleExists != false) { return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $id, $original_title); } return $clean_title; } function delete() { if (!self::canCreateCategory()) { return false; } if (!self::userCanEditCategory($this->id)) { return false; } // cannot delete default category if ($this->id == 1) { return false; } global $global; if (!empty($this->id)) { $_SESSION['getAllCategoriesClearCache'] = 1; $categories_id = self::getSiteCategoryDefaultID(); if ($categories_id) { $sql = "UPDATE videos SET categories_id = ? WHERE categories_id = ?"; sqlDAL::writeSql($sql, "ii", array($categories_id, $this->id)); } $sql = "DELETE FROM categories WHERE id = ?"; } else { return false; } self::clearCacheCount(); self::deleteAssets($this->id); return sqlDAL::writeSql($sql, "i", array($this->id)); } static function deleteAssets($categories_id) { $dirPaths = self::getCategoryDirPath($categories_id); return rrmdir($dirPaths['path']); } /* static function getCategoryType($categoryId) { global $global; $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?;"; $res = sqlDAL::readSql($sql, "i", array($categoryId)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { if (!empty($data)) { return $data; } else { return array("categoryId" => "-1", "type" => "0", "manualSet" => "0"); } } else { return array("categoryId" => "-1", "type" => "0", "manualSet" => "0"); } } - * + * */ static function getCategory($id) { global $global; $id = intval($id); $sql = "SELECT * FROM categories WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($result) { $result['name'] = xss_esc_back($result['name']); } return ($res) ? $result : false; } static function getCategoryByName($name) { global $global; $sql = "SELECT * FROM categories WHERE clean_name = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($name)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($result) { $result['name'] = xss_esc_back($result['name']); } return ($res) ? $result : false; } static function getOrCreateCategoryByName($name) { $cat = self::getCategoryByName($name); if (empty($cat)) { $obj = new Category(0); $obj->setName($name); $obj->setClean_name($name); $obj->setDescription(""); $obj->setIconClass(""); $obj->setNextVideoOrder(0); $obj->setParentId(0); $id = $obj->save(); return self::getCategoryByName($name); } return $cat; } static function getCategoryDefault() { global $global; $sql = "SELECT * FROM categories ORDER BY id ASC LIMIT 1"; $res = sqlDAL::readSql($sql); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($result) { $result['name'] = xss_esc_back($result['name']); } return ($res) ? $result : false; } static function getSiteCategoryDefaultID() { $obj = AVideoPlugin::getObjectDataIfEnabled("PredefinedCategory"); $id = false; if ($obj) { $id = $obj->defaultCategory; } else { $row = self::getCategoryDefault(); if ($row) { $id = $row['id']; } } return $id; } static function getAllCategories($filterCanAddVideoOnly = false, $onlyWithVideos = false) { global $global, $config; if ($config->currentVersionLowerThen('8.4')) { return false; } $sql = "SELECT * FROM categories c WHERE 1=1 "; if (!empty($_GET['parentsOnly'])) { $sql .= "AND parentId = 0 "; } if ($filterCanAddVideoOnly && !User::isAdmin()) { if (is_int($filterCanAddVideoOnly)) { $users_id = $filterCanAddVideoOnly; } else { $users_id = User::getId(); } if ($config->currentVersionGreaterThen('6.1')) { $sql .= " AND (private=0 OR users_id = '{$users_id}') "; } } if ($onlyWithVideos) { $sql .= " AND (SELECT count(*) FROM videos where categories_id = c.id OR categories_id IN (SELECT id from categories where parentId = c.id)) > 0 "; } if (isset($_POST['sort']['title'])) { unset($_POST['sort']['title']); } $sql .= BootGrid::getSqlFromPost(array('name'), "", " ORDER BY `order`, name ASC "); $cacheName = md5($sql); if (empty($_SESSION['getAllCategoriesClearCache'])) { $category = object_to_array(ObjectYPT::getCache($cacheName, 36000)); } else { _session_start(); unset($_SESSION['getAllCategoriesClearCache']); } if (empty($category)) { $res = sqlDAL::readSql($sql); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $category = array(); if ($res) { foreach ($fullResult as $row) { $row['name'] = xss_esc_back($row['name']); $row['total'] = self::getTotalVideosFromCategory($row['id']); $row['fullTotal'] = self::getTotalVideosFromCategory($row['id'], false, true, true); $row['owner'] = User::getNameIdentificationById(@$row['users_id']); $row['canEdit'] = self::userCanEditCategory($row['id']); $row['canAddVideo'] = self::userCanAddInCategory($row['id']); $row['hierarchy'] = self::getHierarchyString($row['parentId']); $row['hierarchyAndName'] = $row['hierarchy'] . $row['name']; $category[] = $row; } //$category = $res->fetch_all(MYSQLI_ASSOC); ObjectYPT::setCache($cacheName, $category); } else { $category = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } return $category; } static function getHierarchyArray($categories_id, $hierarchyArray = array()) { if (empty($categories_id)) { return $hierarchyArray; } $sql = "SELECT * FROM categories WHERE id=? "; $res = sqlDAL::readSql($sql, "i", array($categories_id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($result) { $hierarchyArray[] = $result; return self::getHierarchyArray($result['parentId'], $hierarchyArray); } return $hierarchyArray; } static function getHierarchyString($categories_id) { if (empty($categories_id)) { return "/"; } $array = array_reverse(self::getHierarchyArray($categories_id)); //$array = (self::getHierarchyArray($categories_id)); //var_dump($array);exit; if (empty($array)) { return "/"; } $str = "/"; foreach ($array as $value) { $str .= xss_esc_back($value['name']) . "/"; } return $str; } static function userCanAddInCategory($categories_id, $users_id = 0) { if (empty($categories_id)) { return false; } if (empty($users_id)) { $users_id = User::getId(); } if (empty($users_id)) { return false; } $cat = new Category($categories_id); if (empty($cat->getPrivate()) || $users_id == $cat->getUsers_id()) { return true; } return false; } static function userCanEditCategory($categories_id, $users_id = 0) { if (empty($categories_id)) { return false; } if (empty($users_id)) { $users_id = User::getId(); } if (empty($users_id)) { return false; } if (User::isAdmin()) { return true; } $cat = new Category($categories_id); if ($users_id == $cat->getUsers_id()) { return true; } return false; } static function canCreateCategory() { global $advancedCustomUser; if (User::isAdmin()) { return true; } if ($advancedCustomUser && $advancedCustomUser->usersCanCreateNewCategories && User::canUpload()) { return true; } return false; } static function getChildCategories($parentId, $filterCanAddVideoOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('8.4')) { return false; } $sql = "SELECT * FROM categories WHERE parentId=? AND id!=? "; if ($filterCanAddVideoOnly && !User::isAdmin()) { if (is_int($filterCanAddVideoOnly)) { $users_id = $filterCanAddVideoOnly; } else { $users_id = User::getId(); } if ($config->currentVersionGreaterThen('6.1')) { $sql .= " AND (private=0 OR users_id = '{$users_id}') "; } } $sql .= BootGrid::getSqlFromPost(array('name'), "", " ORDER BY `order`, name ASC "); $res = sqlDAL::readSql($sql, "ii", array($parentId, $parentId)); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $category = array(); if ($res) { foreach ($fullResult as $row) { $row['name'] = xss_esc_back($row['name']); $row['total'] = self::getTotalVideosFromCategory($row['id']); $category[] = $row; } } else { $category = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $category; } static function getChildCategoriesFromTitle($clean_title) { $row = self::getCategoryByName($clean_title); return self::getChildCategories($row['id']); } static function getTotalVideosFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) { global $global, $config; if ($renew || empty($_SESSION['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)])) { $sql = "SELECT count(id) as total FROM videos v WHERE 1=1 AND categories_id = ? "; if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } if (!$getAllVideos) { $sql .= Video::getUserGroupsCanSeeSQL(); } //echo $categories_id, $sql;exit; $res = sqlDAL::readSql($sql, "i", array($categories_id)); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); $rows = self::getChildCategories($categories_id); foreach ($rows as $value) { $total += self::getTotalVideosFromCategory($value['id'], $showUnlisted, $getAllVideos, $renew); } _session_start(); $_SESSION['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)] = $total; } return $_SESSION['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]; } static function clearCacheCount() { // clear category count cache _session_start(); unset($_SESSION['categoryTotal']); $_SESSION['getAllCategoriesClearCache'] = 1; //session_write_close(); } static function getTotalCategories($filterCanAddVideoOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('5.01')) { return false; } $sql = "SELECT id, parentId FROM categories WHERE 1=1 "; if ($filterCanAddVideoOnly && !User::isAdmin()) { if (is_int($filterCanAddVideoOnly)) { $users_id = $filterCanAddVideoOnly; } else { $users_id = User::getId(); } if ($config->currentVersionGreaterThen('6.1')) { $sql .= " AND (private=0 OR users_id = '{$users_id}') "; } } if (!empty($_GET['parentsOnly'])) { $sql .= "AND parentId = 0 OR parentId = -1 "; } $sql .= BootGrid::getSqlSearchFromPost(array('name')); $res = sqlDAL::readSql($sql); $numRows = sqlDal::num_rows($res); sqlDAL::close($res); return $numRows; } function getIconClass() { if (empty($this->iconClass)) { return "fa fa-folder"; } return $this->iconClass; } function setIconClass($iconClass) { $this->iconClass = $iconClass; } function getName() { return $this->name; } function getClean_name() { return $this->clean_name; } function getDescription() { return $this->description; } function getAllow_download() { return $this->allow_download; } function setAllow_download($allow_download) { $this->allow_download = intval($allow_download); } static function getCategoryDirPath($categories_id = "") { global $global; $dir = "videos/categories/assets/"; if (!empty($categories_id)) { $dir .= $categories_id . "/"; } $path = array(); $path['dir'] = "{$global['systemRootPath']}{$dir}"; make_path($path['dir']); $path['path'] = "{$global['systemRootPath']}{$dir}"; $path['url'] = "{$global['webSiteRootURL']}{$dir}"; return $path; } static function isAssetsValids($categories_id) { $photo = Category::getCategoryPhotoPath($categories_id); $background = Category::getCategoryBackgroundPath($categories_id); if(!file_exists($photo['path']) || !file_exists($background['path'])){ return false; } return true; } static function getCategoryPhotoPath($categories_id) { return self::getCategoryAssetPath("photo.png", $categories_id); } static function getCategoryBackgroundPath($categories_id) { return self::getCategoryAssetPath("background.png", $categories_id); } private static function getCategoryAssetPath($name, $categories_id) { if (empty($categories_id)) { return false; } if (empty($name)) { return false; } $dirPaths = self::getCategoryDirPath($categories_id); global $global; $path = array(); $path['dir'] = $dirPaths['url']; $path['path'] = "{$dirPaths['path']}{$name}"; $path['url'] = "{$dirPaths['url']}{$name}"; if (file_exists($path['path'])) { $path['url+timestamp'] = "{$path['url']}?" . filectime($path['path']); } else { $path['url+timestamp'] = $path['url']; } return $path; } } diff --git a/objects/comment.php b/objects/comment.php index ea3bd083e..42a35a99c 100644 --- a/objects/comment.php +++ b/objects/comment.php @@ -1,347 +1,358 @@ comment = xss_esc($comment); $this->videos_id = $videos_id; $this->users_id = User::getId(); } else { // get data from id $this->load($id); } - } - function getId() { + public function getId() + { return $this->id; } - function setComments_id_pai($comments_id_pai) { + public function setComments_id_pai($comments_id_pai) + { $this->comments_id_pai = $comments_id_pai; } - function getComments_id_pai() { + public function getComments_id_pai() + { return $this->comments_id_pai; } - function getUsers_id() { + public function getUsers_id() + { return $this->users_id; } - function setComment($comment) { + public function setComment($comment) + { $this->comment = xss_esc($comment); } - function getVideos_id() { + public function getVideos_id() + { return $this->videos_id; } - private function load($id) { + private function load($id) + { $row = $this->getComment($id); - if (empty($row)) + if (empty($row)) { return false; + } foreach ($row as $key => $value) { $this->$key = $value; } return true; } - function save() { + public function save() + { global $global; - if(!User::isLogged()){ + if (!User::isLogged()) { header('Content-Type: application/json'); die('{"error":"'.__("Permission denied").'"}'); } //$this->comment = htmlentities($this->comment); $this->comment = $global['mysqli']->real_escape_string($this->comment); - if(empty($this->comment)){ + if (empty($this->comment)) { return false; } - if(empty($this->comments_id_pai)){ + if (empty($this->comments_id_pai)) { $this->comments_id_pai = 'NULL'; } - if(empty($this->videos_id) && !empty($this->comments_id_pai)){ + if (empty($this->videos_id) && !empty($this->comments_id_pai)) { $comment = new Comment("", 0, $this->comments_id_pai); $this->videos_id = $comment->getVideos_id(); } - if (!empty($this->id) ) { - if(!self::userCanAdminComment($this->id)){ + if (!empty($this->id)) { + if (!self::userCanAdminComment($this->id)) { return false; } $sql = "UPDATE comments SET " . " comment = ?, modified = now() WHERE id = ?"; - $resp = sqlDAL::writeSql($sql,"si",array(xss_esc($this->comment),$this->id)); + $resp = sqlDAL::writeSql($sql, "si", array(xss_esc($this->comment),$this->id)); } else { $id = User::getId(); $sql = "INSERT INTO comments ( comment,users_id, videos_id, comments_id_pai, created, modified) VALUES " . " (?, ?, ?, {$this->comments_id_pai}, now(), now())"; - $resp = sqlDAL::writeSql($sql,"sii",array(xss_esc($this->comment),$id,$this->videos_id)); + $resp = sqlDAL::writeSql($sql, "sii", array(xss_esc($this->comment),$id,$this->videos_id)); } - if((empty($resp))&&($global['mysqli']->errno!=0)){ + if ((empty($resp))&&($global['mysqli']->errno!=0)) { die('Error (comment save) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } if (empty($this->id)) { // log_error("note: insert_id works? ".$global['mysqli']->insert_id); // success! $id = $global['mysqli']->insert_id; $this->id = $id; } else { $id = $this->id; } - if(empty($this->comments_id_pai) || $this->comments_id_pai== 'NULL'){ + if (empty($this->comments_id_pai) || $this->comments_id_pai== 'NULL') { AVideoPlugin::afterNewComment($this->id); - }else{ + } else { AVideoPlugin::afterNewResponse($this->id); } return $resp; } - - function delete() { - if(!self::userCanAdminComment($this->id)){ + public function delete() + { + if (!self::userCanAdminComment($this->id)) { return false; } global $global; if (!empty($this->id)) { $sql = "DELETE FROM comments WHERE id = ?"; } else { return false; } - return sqlDAL::writeSql($sql,"i",array($this->id)); + return sqlDAL::writeSql($sql, "i", array($this->id)); } - private function getComment($id) { + private function getComment($id) + { global $global; $id = intval($id); $sql = "SELECT * FROM comments WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql,"i",array($id)); + $res = sqlDAL::readSql($sql, "i", array($id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return ($res!=false) ? $result : false; } - static function getAllComments($videoId = 0, $comments_id_pai = 'NULL') { + public static function getAllComments($videoId = 0, $comments_id_pai = 'NULL') + { global $global; $format = ""; $values = array(); $sql = "SELECT c.*, u.name as name, u.user as user, " . " (SELECT count(id) FROM comments_likes as l where l.comments_id = c.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM comments_likes as l where l.comments_id = c.id AND `like` = -1 ) as dislikes "; if (User::isLogged()) { $sql .= ", (SELECT `like` FROM comments_likes as l where l.comments_id = c.id AND users_id = ? ) as myVote "; $format .= "i"; $values[]=User::getId(); } else { $sql .= ", 0 as myVote "; } $sql .= " FROM comments c LEFT JOIN users as u ON u.id = users_id LEFT JOIN videos as v ON v.id = videos_id WHERE 1=1 "; if (!empty($videoId)) { $sql .= " AND videos_id = ? "; $format .= "i"; $values[] = $videoId; - }else if(!Permissions::canAdminComment() && empty ($comments_id_pai)){ - if(!User::isLogged()){ + } elseif (!Permissions::canAdminComment() && empty($comments_id_pai)) { + if (!User::isLogged()) { die("can not see comments"); } $users_id = User::getId(); $sql .= " AND (v.users_id = ? OR c.users_id = ?) "; $format .= "ii"; $values[]=$users_id; $values[]=$users_id; } - if($comments_id_pai==='NULL' || empty ($comments_id_pai)){ + if ($comments_id_pai==='NULL' || empty($comments_id_pai)) { $sql .= " AND (comments_id_pai IS NULL "; - if(empty($videoId) && User::isLogged()){ + if (empty($videoId) && User::isLogged()) { $users_id = User::getId(); $sql .= " OR c.users_id = ? "; $format .= "i"; $values[]=$users_id; } $sql .= ") "; - }else{ + } else { $sql .= " AND comments_id_pai = ? "; $format .= "s"; $values[]=$comments_id_pai; } $sql .= BootGrid::getSqlFromPost(array('name')); - $res = sqlDAL::readSql($sql,$format,$values); + $res = sqlDAL::readSql($sql, $format, $values); $allData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $comment = array(); if ($res!=false) { foreach ($allData as $row) { $row['comment'] = str_replace('\n', "\n", $row['comment']); $row['commentPlain'] = xss_esc_back($row['comment']); $row['commentHTML'] = nl2br($row['commentPlain']); $comment[] = $row; } //$comment = $res->fetch_all(MYSQLI_ASSOC); } else { $comment = false; die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $comment; } - static function getTotalComments($videoId = 0, $comments_id_pai = 'NULL', $video_owner_users_id=0) { + public static function getTotalComments($videoId = 0, $comments_id_pai = 'NULL', $video_owner_users_id=0) + { global $global; $format = ""; $values = array(); $sql = "SELECT c.id FROM comments c LEFT JOIN users as u ON u.id = users_id LEFT JOIN videos as v ON v.id = videos_id WHERE 1=1 "; if (!empty($videoId)) { $sql .= " AND videos_id = ? "; $format .= "i"; $values[] = $videoId; - }else if(!Permissions::canAdminComment() && empty ($comments_id_pai)){ - if(!User::isLogged()){ + } elseif (!Permissions::canAdminComment() && empty($comments_id_pai)) { + if (!User::isLogged()) { die("can not see comments"); } $users_id = User::getId(); $sql .= " AND (v.users_id = ? OR c.users_id = ?) "; $format .= "ii"; $values[] = $users_id; $values[] = $users_id; } - if($comments_id_pai==='NULL' || empty ($comments_id_pai)){ + if ($comments_id_pai==='NULL' || empty($comments_id_pai)) { $sql .= " AND (comments_id_pai IS NULL "; - if(empty($videoId) && User::isLogged()){ + if (empty($videoId) && User::isLogged()) { $users_id = User::getId(); $sql .= " OR c.users_id = ? "; $format .= "i"; $values[] = $users_id; } $sql .= ") "; - }else{ + } else { $sql .= " AND comments_id_pai = ? "; $format .= "s"; $values[] = $comments_id_pai; } - if(!empty($video_owner_users_id)){ + if (!empty($video_owner_users_id)) { $sql .= " AND v.users_id = ? "; $format .= "i"; $values[] = $video_owner_users_id; } $sql .= BootGrid::getSqlSearchFromPost(array('name')); - $res = sqlDAL::readSql($sql,$format,$values); + $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); return $countRow; } - static function userCanAdminComment($comments_id){ - if(!User::isLogged()){ + public static function userCanAdminComment($comments_id) + { + if (!User::isLogged()) { return false; } - if(Permissions::canAdminComment()){ + if (Permissions::canAdminComment()) { return true; } $obj = new Comment("", 0, $comments_id); - if($obj->users_id == User::getId()){ + if ($obj->users_id == User::getId()) { return true; } $video = new Video("", "", $obj->videos_id); - if($video->getUsers_id() == User::getId()){ + if ($video->getUsers_id() == User::getId()) { return true; } return false; } - - static function userCanEditComment($comments_id){ - if(!User::isLogged()){ + + public static function userCanEditComment($comments_id) + { + if (!User::isLogged()) { return false; } - if(Permissions::canAdminComment()){ + if (Permissions::canAdminComment()) { return true; } $obj = new Comment("", 0, $comments_id); - if($obj->users_id == User::getId()){ + if ($obj->users_id == User::getId()) { return true; } return false; } - static function getTotalCommentsThumbsUpFromUser($users_id, $startDate, $endDate) { + public static function getTotalCommentsThumbsUpFromUser($users_id, $startDate, $endDate) + { global $global; $sql = "SELECT id from comments WHERE users_id = ?"; - $res = sqlDAL::readSql($sql,"i",array($users_id)); + $res = sqlDAL::readSql($sql, "i", array($users_id)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $r = array('thumbsUp'=>0, 'thumbsDown'=>0 ); if ($res!=false) { foreach ($fullData as $row) { $format = "i"; $values = array($row['id']); $sql = "SELECT id from comments_likes WHERE comments_id = ? AND `like` = 1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } - if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } - $res = sqlDAL::readSql($sql,$format,$values); + $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsUp']+=$countRow; - $format = "i"; $values = array($row['id']); $sql = "SELECT id from comments_likes WHERE comments_id = ? AND `like` = -1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } - if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } - $res = sqlDAL::readSql($sql,$format,$values); + $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsDown']+=$countRow; } } - return $r; } - - - } diff --git a/objects/comments_like.php b/objects/comments_like.php index 3da7be605..123046d27 100644 --- a/objects/comments_like.php +++ b/objects/comments_like.php @@ -1,152 +1,163 @@ comments_id = $comments_id; $this->users_id = User::getId(); $this->load(); // if click again in the same vote, remove the vote if ($this->like == $like) { $like = 0; } $this->setLike($like); $this->save(); } - private function setLike($like) { + private function setLike($like) + { $like = intval($like); - if(!in_array($like, array(0,1,-1))){ + if (!in_array($like, array(0,1,-1))) { $like = 0; } $this->like = $like; } - private function load() { + private function load() + { $like = $this->getLike(); if (empty($like)) { return false; } foreach ($like as $key => $value) { $this->$key = $value; } } - private function getLike() { + private function getLike() + { global $global; if (empty($this->users_id) || empty($this->comments_id)) { header('Content-Type: application/json'); die('{"error":"You must have user and videos set to get a like"}'); } $sql = "SELECT * FROM comments_likes WHERE users_id = ? AND comments_id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql,"ii",array($this->users_id,$this->comments_id)); + $res = sqlDAL::readSql($sql, "ii", array($this->users_id,$this->comments_id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return ($res) ? $result : false; } - private function save() { + private function save() + { global $global; - if(!User::isLogged()){ + if (!User::isLogged()) { header('Content-Type: application/json'); die('{"error":"'.__("Permission denied").'"}'); } $formats = ""; $values = array(); if (!empty($this->id)) { $sql = "UPDATE comments_likes SET `like` = ?, modified = now() WHERE id = ?"; $formats = "ii"; $values = array($this->like,$this->id); } else { $sql = "INSERT INTO comments_likes ( `like`,users_id, comments_id, created, modified) VALUES (?, ?, ?, now(), now())"; $formats = "iii"; $values = array($this->like,$this->users_id,$this->comments_id); } - return sqlDAL::writeSql($sql,$formats,$values); + return sqlDAL::writeSql($sql, $formats, $values); } - static function getLikes($comments_id) { + public static function getLikes($comments_id) + { global $global; $obj = new stdClass(); $obj->comments_id = $comments_id; $obj->likes = 0; $obj->dislikes = 0; $obj->myVote = self::getMyVote($comments_id); $sql = "SELECT count(*) as total FROM comments_likes WHERE comments_id = ? AND `like` = 1 "; // like - $res = sqlDAL::readSql($sql,"i",array($comments_id)); + $res = sqlDAL::readSql($sql, "i", array($comments_id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!$res) { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->likes = intval($result['total']); $sql = "SELECT count(*) as total FROM comments_likes WHERE comments_id = ? AND `like` = -1 "; // dislike - $res = sqlDAL::readSql($sql,"i",array($comments_id)); + $res = sqlDAL::readSql($sql, "i", array($comments_id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!$res) { die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->dislikes = intval($result['total']); return $obj; } - - static function getTotalLikes() { + + public static function getTotalLikes() + { global $global; $obj = new stdClass(); $obj->likes = 0; $obj->dislikes = 0; $sql = "SELECT count(*) as total FROM comments_likes WHERE `like` = 1 "; // like $res = sqlDAL::readSql($sql); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!$res) { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->likes = intval($result['total']); $sql = "SELECT count(*) as total FROM comments_likes WHERE `like` = -1 "; // dislike $res = sqlDAL::readSql($sql); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!$res) { die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->dislikes = intval($result['total']); return $obj; } - static function getMyVote($comments_id) { + public static function getMyVote($comments_id) + { global $global; if (!User::isLogged()) { return 0; } $id = User::getId(); $sql = "SELECT `like` FROM comments_likes WHERE comments_id = ? AND users_id = ? "; // like - $res = sqlDAL::readSql($sql,"ii",array($comments_id,$id)); + $res = sqlDAL::readSql($sql, "ii", array($comments_id,$id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { return intval($result['like']); } return 0; } - } diff --git a/objects/configuration.php b/objects/configuration.php index 542cd9144..87803a42a 100644 --- a/objects/configuration.php +++ b/objects/configuration.php @@ -1,510 +1,510 @@ load(); if (!empty($video_resolution)) { $this->video_resolution = $video_resolution; } } function load() { global $global; $sql = "SELECT * FROM configurations WHERE id = 1 LIMIT 1"; //echo $sql;exit; // add true because I was not getting the SMTP configuration on function setSiteSendMessage(&$mail) $res = sqlDAL::readSql($sql, "", array(), true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res && !empty($result)) { $config = $result; //var_dump($config);exit; foreach ($config as $key => $value) { $this->$key = $value; } } else { return false; } } function save() { global $global; if (!User::isAdmin()) { header('Content-Type: application/json'); die('{"error":"' . __("Permission denied") . '"}'); } $this->users_id = User::getId(); ObjectYPT::deleteCache("getEncoderURL"); $sql = "UPDATE configurations SET " . "video_resolution = '{$this->video_resolution}'," . "webSiteTitle = '{$this->webSiteTitle}'," . "language = '{$this->language}'," . "contactEmail = '{$this->contactEmail}'," . "users_id = '{$this->users_id}', " . "authCanUploadVideos = '{$this->authCanUploadVideos}'," . "authCanViewChart = '{$this->authCanViewChart}'," . "authCanComment = '{$this->authCanComment}'," . "encoderURL = '{$global['mysqli']->real_escape_string($this->_getEncoderURL())}'," . "head = '{$global['mysqli']->real_escape_string($this->getHead())}'," . "adsense = '{$global['mysqli']->real_escape_string($this->getAdsense())}'," . "mode = '{$this->getMode()}'," . "logo = '{$global['mysqli']->real_escape_string($this->getLogo())}'," . "logo_small = '{$global['mysqli']->real_escape_string($this->getLogo_small())}'," . "disable_analytics = '{$this->getDisable_analytics()}'," . "disable_youtubeupload = '{$this->getDisable_youtubeupload()}'," . "allow_download = '{$this->getAllow_download()}'," . "session_timeout = '{$this->getSession_timeout()}'," . "autoplay = '{$this->getAutoplay()}'," . "theme = '{$global['mysqli']->real_escape_string($this->getTheme())}'," . "smtp = '{$this->getSmtp()}'," . "smtpAuth = '{$this->getSmtpAuth()}'," . "smtpSecure = '{$global['mysqli']->real_escape_string($this->getSmtpSecure())}'," . "smtpHost = '{$global['mysqli']->real_escape_string($this->getSmtpHost())}'," . "smtpUsername = '{$global['mysqli']->real_escape_string($this->getSmtpUsername())}'," . "smtpPort = '{$global['mysqli']->real_escape_string($this->getSmtpPort())}'," . "smtpPassword = '{$global['mysqli']->real_escape_string($this->getSmtpPassword())}'" . " WHERE id = 1"; return sqlDAL::writeSql($sql); } function getVideo_resolution() { return $this->video_resolution; } function getUsers_id() { return $this->users_id; } function getVersion() { if (empty($this->version)) { return " 0.1"; } return $this->version; } function getWebSiteTitle() { return $this->webSiteTitle; } function getLanguage() { if ($this->language == "en") { return "us"; } return $this->language; } function getContactEmail() { return $this->contactEmail; } function setVideo_resolution($video_resolution) { $this->video_resolution = $video_resolution; } function setWebSiteTitle($webSiteTitle) { $this->webSiteTitle = $webSiteTitle; } function setLanguage($language) { $this->language = $language; } function setContactEmail($contactEmail) { $this->contactEmail = $contactEmail; } function currentVersionLowerThen($version) { return version_compare($version, $this->getVersion()) > 0; } function currentVersionGreaterThen($version) { return version_compare($version, $this->getVersion()) < 0; } function currentVersionEqual($version) { return version_compare($version, $this->getVersion()) == 0; } function getAuthCanUploadVideos() { return $this->authCanUploadVideos; } function getAuthCanViewChart() { return $this->authCanViewChart; } function getAuthCanComment() { return $this->authCanComment; } function setAuthCanUploadVideos($authCanUploadVideos) { $this->authCanUploadVideos = intval($authCanUploadVideos); } function setAuthCanViewChart($authCanViewChart) { $this->authCanViewChart = $authCanViewChart; } function setAuthCanComment($authCanComment) { $this->authCanComment = $authCanComment; } function getHead() { return $this->head; } function getLogo($timestamp = false) { global $global; if (empty($this->logo)) { return "view/img/logo.png"; } $get = ""; $file = str_replace("?", "", $global['systemRootPath'] . $this->logo); if ($timestamp && file_exists($file)) { $get .= "?" . filemtime($file); } return $this->logo . $get; } static function _getFavicon($getPNG = false) { global $global; $file = false; $url = false; if (!$getPNG) { $file = $global['systemRootPath'] . "videos/favicon.ico"; $url = "{$global['webSiteRootURL']}videos/favicon.ico"; if (!file_exists($file)) { $file = $global['systemRootPath'] . "view/img/favicon.ico"; $url = "{$global['webSiteRootURL']}view/img/favicon.ico"; } } if (empty($url) || !file_exists($file)) { $file = $global['systemRootPath'] . "videos/favicon.png"; $url = "{$global['webSiteRootURL']}videos/favicon.png"; if (!file_exists($file)) { $file = $global['systemRootPath'] . "view/img/favicon.png"; $url = "{$global['webSiteRootURL']}view/img/favicon.png"; } } return array('file' => $file, 'url' => $url); } function getFavicon($getPNG = false, $getTime = true) { $return = self::_getFavicon($getPNG); if ($getTime) { return $return['url'] . "?" . filemtime($return['file']); } else { return $return['url']; } } static function getOGImage() { global $global; $destination = "{$global['systemRootPath']}videos/cache/og_200X200.jpg"; $return = self::_getFavicon(true); convertImageToOG($return['file'], $destination); return $global['webSiteRootURL'] . "videos/cache/og_200X200.jpg"; } function setHead($head) { $this->head = $head; } function setLogo($logo) { $this->logo = $logo; } function getLogo_small() { if (empty($this->logo_small)) { return "view/img/logo32.png"; } return $this->logo_small; } function setLogo_small($logo_small) { $this->logo_small = $logo_small; } function getAdsense() { return $this->adsense; } function setAdsense($adsense) { $this->adsense = $adsense; } function getMode() { if (empty($this->mode)) { return 'Youtube'; } return $this->mode; } function setMode($mode) { $this->mode = $mode; } // version 2.7 function getDisable_analytics() { return $this->disable_analytics; } function getDisable_youtubeupload() { return $this->disable_youtubeupload; } function getAllow_download() { return $this->allow_download; } function getSession_timeout() { return $this->session_timeout; } function setDisable_analytics($disable_analytics) { $this->disable_analytics = ($disable_analytics == 'true' || $disable_analytics == '1') ? 1 : 0; } function setDisable_youtubeupload($disable_youtubeupload) { $this->disable_youtubeupload = ($disable_youtubeupload == 'true' || $disable_youtubeupload == '1') ? 1 : 0; } function setAllow_download($allow_download) { $this->allow_download = ($allow_download == 'true' || $allow_download == '1') ? 1 : 0; } function setSession_timeout($session_timeout) { $this->session_timeout = $session_timeout; } function getAutoplay() { return intval($this->autoplay); } function setAutoplay($autoplay) { $this->autoplay = ($autoplay == 'true' || $autoplay == '1') ? 1 : 0; } // end version 2.7 static function rewriteConfigFile() { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase; if (empty($global['salt'])) { $global['salt'] = uniqid(); } if (empty($global['disableTimeFix'])) { $global['disableTimeFix'] = 0; } if (empty($global['logfile'])) { $global['logfile'] = $global['systemRootPath'] . 'videos/avideo.log'; } $content = "theme)) { return "default"; } return $this->theme; } function setTheme($theme) { $this->theme = $theme; } function getSmtp() { return intval($this->smtp); } function getSmtpAuth() { return intval($this->smtpAuth); } function getSmtpSecure() { return $this->smtpSecure; } function getSmtpHost() { return $this->smtpHost; } function getSmtpUsername() { return $this->smtpUsername; } function getSmtpPassword() { return $this->smtpPassword; } function setSmtp($smtp) { $this->smtp = ($smtp == 'true' || $smtp == '1') ? 1 : 0; } function setSmtpAuth($smtpAuth) { $this->smtpAuth = ($smtpAuth == 'true' || $smtpAuth == '1') ? 1 : 0; } function setSmtpSecure($smtpSecure) { $this->smtpSecure = $smtpSecure; } function setSmtpHost($smtpHost) { $this->smtpHost = $smtpHost; } function setSmtpUsername($smtpUsername) { $this->smtpUsername = $smtpUsername; } function setSmtpPassword($smtpPassword) { $this->smtpPassword = $smtpPassword; } function getSmtpPort() { return intval($this->smtpPort); } function setSmtpPort($smtpPort) { $this->smtpPort = intval($smtpPort); } function _getEncoderURL() { return $this->encoderURL; } function getEncoderURL() { global $getEncoderURL; if (empty($getEncoderURL)) { $getEncoderURL = ObjectYPT::getCache("getEncoderURL", 60); if (empty($getEncoderURL)) { global $advancedCustom; if (!empty($advancedCustom->useEncoderNetworkRecomendation) && !empty($advancedCustom->encoderNetwork)) { if (substr($advancedCustom->encoderNetwork, -1) !== '/') { $advancedCustom->encoderNetwork .= "/"; } $bestEncoder = json_decode(url_get_contents($advancedCustom->encoderNetwork . "view/getBestEncoder.php", "", 10)); if (!empty($bestEncoder->siteURL)) { $this->encoderURL = $bestEncoder->siteURL; } else { error_log("Configuration::getEncoderURL ERROR your network ($advancedCustom->encoderNetwork) is not configured properly This slow down your site a lot, disable the option useEncoderNetworkRecomendation in your CustomizeAdvanced plugin"); } } if (empty($this->encoderURL)) { $getEncoderURL = "https://encoder1.avideo.com/"; } if (substr($this->encoderURL, -1) !== '/') { $this->encoderURL .= "/"; } $getEncoderURL = $this->encoderURL; ObjectYPT::setCache("getEncoderURL", $getEncoderURL); } } return $getEncoderURL; } function setEncoderURL($encoderURL) { $this->encoderURL = $encoderURL; } function getPageTitleSeparator() { if(!defined('PAGE_TITLE_SEPARATOR')){ define("PAGE_TITLE_SEPARATOR", "·"); // This is ready to be configurable, if needed } return " " . PAGE_TITLE_SEPARATOR . " "; } } diff --git a/objects/emailAllUsers.json.php b/objects/emailAllUsers.json.php index 9d492c36b..09d69eadd 100644 --- a/objects/emailAllUsers.json.php +++ b/objects/emailAllUsers.json.php @@ -1,64 +1,73 @@ error = false; $obj->msg = array(); //Create a new PHPMailer instance $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //Set who the message is to be sent from $mail->setFrom($config->getContactEmail()); $mail->Subject = 'Message From Site ' . $config->getWebSiteTitle(); $mail->msgHTML($_POST['message']); $count = 0; $currentCount = 0; foreach ($users as $value) { if ($count % $mailsLimit === 0) { if ($count !== 0) { if (!$mail->send()) { $obj->error = true; $obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo; } $mail->ClearAddresses(); $mail->ClearCCs(); $mail->ClearBCCs(); $currentCount = 0; } } $mail->addBCC($value["email"]); $count++; $currentCount++; } if ($currentCount && !$mail->send()) { $obj->error = true; $obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo; } $obj->count = $count; echo json_encode($obj); diff --git a/objects/encryptPass.json.php b/objects/encryptPass.json.php index 3189bb6e3..56a0cffc9 100644 --- a/objects/encryptPass.json.php +++ b/objects/encryptPass.json.php @@ -1,15 +1,12 @@ password = @$_REQUEST['pass']; $obj->encryptedPassword=encryptPassword($obj->password); echo json_encode($obj); - - - diff --git a/objects/functionCroppie.php b/objects/functionCroppie.php index d637d163a..0744a0b51 100644 --- a/objects/functionCroppie.php +++ b/objects/functionCroppie.php @@ -1,61 +1,61 @@
- +
\ No newline at end of file + diff --git a/objects/functiongetOpenGraph.php b/objects/functiongetOpenGraph.php index 50c718614..612120c9a 100644 --- a/objects/functiongetOpenGraph.php +++ b/objects/functiongetOpenGraph.php @@ -1,106 +1,106 @@ "; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); $imgw = 1024; $imgh = 768; if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } else if ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $twitter_site = $advancedCustom->twitter_site; ?> twitter_player)) { ?> - + twitter_summary_large_image)) { ?> - + - +
-

(Iframe):

+

(Iframe):

(Object):

-

(HTML):

+

(HTML):

-

(BBCode):

+

(BBCode):

disableEmailSharing)) { ?>
" class="form-control" type="text">
" class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText">
-
+ diff --git a/objects/functionogSite.php b/objects/functionogSite.php index 381cd9ed5..abca8d65c 100644 --- a/objects/functionogSite.php +++ b/objects/functionogSite.php @@ -1,54 +1,54 @@ "; if ($users_id = isChannel()) { $imgw = 200; $imgh = 200; $img = User::getOGImage($users_id); $title = User::getNameIdentificationById($users_id); $url = User::getChannelLink($users_id); ?> getWebSiteTitle()); $url = $global['webSiteRootURL']; ?> twitter_summary_large_image)) { ?> - + - + diff --git a/objects/functions.php b/objects/functions.php index e91f4f930..5a05c9746 100644 --- a/objects/functions.php +++ b/objects/functions.php @@ -1,5133 +1,5133 @@ 0 && $upload_max < $max_size) { $max_size = $upload_max; } } return $max_size; } function parse_size($size) { $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. if ($unit) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } } function humanFileSize($size, $unit = "") { if ((!$unit && $size >= 1 << 30) || $unit == "GB") { return number_format($size / (1 << 30), 2) . "GB"; } if ((!$unit && $size >= 1 << 20) || $unit == "MB") { return number_format($size / (1 << 20), 2) . "MB"; } if ((!$unit && $size >= 1 << 10) || $unit == "KB") { return number_format($size / (1 << 10), 2) . "KB"; } return number_format($size) . " bytes"; } function get_max_file_size() { return humanFileSize(file_upload_max_size()); } function humanTiming($time, $precision = 0) { if (!is_int($time)) { $time = strtotime($time); } $time = time() - $time; // to get the time since that moment return secondsToHumanTiming($time, $precision); } function humanTimingAgo($time, $precision = 0) { if (!is_int($time)) { $time = strtotime($time); } $time = time() - $time; // to get the time since that moment if (empty($time)) { return __("Now"); } return secondsToHumanTiming($time, $precision) . " " . __("ago"); } function secondsToHumanTiming($time, $precision = 0) { if (empty($time)) { return __("Now"); } $time = ($time < 0) ? $time * -1 : $time; $time = ($time < 1) ? 1 : $time; $tokens = array( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second', ); /** * For detection propouse only */ __('year'); __('month'); __('week'); __('day'); __('hour'); __('minute'); __('second'); __('years'); __('months'); __('weeks'); __('days'); __('hours'); __('minutes'); __('seconds'); foreach ($tokens as $unit => $text) { if ($time < $unit) { continue; } $numberOfUnits = floor($time / $unit); if ($numberOfUnits > 1) { $text = __($text . "s"); } else { $text = __($text); } if ($precision) { $rest = $time % $unit; if ($rest) { $text .= ' ' . secondsToHumanTiming($rest, $precision - 1); } } return $numberOfUnits . ' ' . $text; } } function checkVideosDir() { $dir = "../videos"; if (file_exists($dir)) { return is_writable($dir); } return mkdir($dir); } function isApache() { return (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false); } function isPHP($version = "'7.0.0'") { return (version_compare(PHP_VERSION, $version) >= 0); } function modEnabled($mod_name) { if (!function_exists('apache_get_modules')) { ob_start(); phpinfo(INFO_MODULES); $contents = ob_get_contents(); ob_end_clean(); return (strpos($contents, 'mod_' . $mod_name) !== false); } return in_array('mod_' . $mod_name, apache_get_modules()); } function modRewriteEnabled() { return modEnabled("rewrite"); } function modAliasEnabled() { return modEnabled("alias"); } function isFFMPEG() { return trim(shell_exec('which ffmpeg')); } function isUnzip() { return trim(shell_exec('which unzip')); } function isExifToo() { return trim(shell_exec('which exiftool')); } function getPathToApplication() { return str_replace("install/index.php", "", $_SERVER["SCRIPT_FILENAME"]); } function getURLToApplication() { $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = explode("install/index.php", $url); return $url[0]; } //max_execution_time = 7200 function check_max_execution_time() { $max_size = ini_get('max_execution_time'); $recomended_size = 7200; return ($recomended_size <= $max_size); } //post_max_size = 100M function check_post_max_size() { $max_size = parse_size(ini_get('post_max_size')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //upload_max_filesize = 100M function check_upload_max_filesize() { $max_size = parse_size(ini_get('upload_max_filesize')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //memory_limit = 100M function check_memory_limit() { $max_size = parse_size(ini_get('memory_limit')); $recomended_size = parse_size('512M'); return ($recomended_size <= $max_size); } function check_mysqlnd() { return function_exists('mysqli_fetch_all'); } function base64DataToImage($imgBase64) { $img = $imgBase64; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); return base64_decode($img); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (!empty($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "127.0.0.1"; } return $ip; } function cleanString($text) { $utf8 = array( '/[áàâãªä]/u' => 'a', '/[ÁÀÂÃÄ]/u' => 'A', '/[ÍÌÎÏ]/u' => 'I', '/[íìîï]/u' => 'i', '/[éèêë]/u' => 'e', '/[ÉÈÊË]/u' => 'E', '/[óòôõºö]/u' => 'o', '/[ÓÒÔÕÖ]/u' => 'O', '/[úùûü]/u' => 'u', '/[ÚÙÛÜ]/u' => 'U', '/ç/' => 'c', '/Ç/' => 'C', '/ñ/' => 'n', '/Ñ/' => 'N', '/–/' => '-', // UTF-8 hyphen to 'normal' hyphen '/[’‘‹›‚]/u' => ' ', // Literally a single quote '/[“”«»„]/u' => ' ', // Double quote '/ /' => ' ', // nonbreaking space (equiv. to 0x160) '/Є/' => 'YE', '/І/' => 'I', '/Ѓ/' => 'G', '/і/' => 'i', '/№/' => '#', '/є/' => 'ye', '/ѓ/' => 'g', '/А/' => 'A', '/Б/' => 'B', '/В/' => 'V', '/Г/' => 'G', '/Д/' => 'D', '/Е/' => 'E', '/Ё/' => 'YO', '/Ж/' => 'ZH', '/З/' => 'Z', '/И/' => 'I', '/Й/' => 'J', '/К/' => 'K', '/Л/' => 'L', '/М/' => 'M', '/Н/' => 'N', '/О/' => 'O', '/П/' => 'P', '/Р/' => 'R', '/С/' => 'S', '/Т/' => 'T', '/У/' => 'U', '/Ф/' => 'F', '/Х/' => 'H', '/Ц/' => 'C', '/Ч/' => 'CH', '/Ш/' => 'SH', '/Щ/' => 'SHH', '/Ъ/' => '', '/Ы/' => 'Y', '/Ь/' => '', '/Э/' => 'E', '/Ю/' => 'YU', '/Я/' => 'YA', '/а/' => 'a', '/б/' => 'b', '/в/' => 'v', '/г/' => 'g', '/д/' => 'd', '/е/' => 'e', '/ё/' => 'yo', '/ж/' => 'zh', '/з/' => 'z', '/и/' => 'i', '/й/' => 'j', '/к/' => 'k', '/л/' => 'l', '/м/' => 'm', '/н/' => 'n', '/о/' => 'o', '/п/' => 'p', '/р/' => 'r', '/с/' => 's', '/т/' => 't', '/у/' => 'u', '/ф/' => 'f', '/х/' => 'h', '/ц/' => 'c', '/ч/' => 'ch', '/ш/' => 'sh', '/щ/' => 'shh', '/ъ/' => '', '/ы/' => 'y', '/ь/' => '', '/э/' => 'e', '/ю/' => 'yu', '/я/' => 'ya', '/—/' => '-', '/«/' => '', '/»/' => '', '/…/' => '' ); return preg_replace(array_keys($utf8), array_values($utf8), $text); } function cleanURLName($name) { $name = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\]%" ]+/', '-', trim(strtolower(cleanString($name)))); return trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $name), "-"); } /** * @brief return true if running in CLI, false otherwise * if is set $_GET['ignoreCommandLineInterface'] will return false * @return boolean */ function isCommandLineInterface() { return (empty($_GET['ignoreCommandLineInterface']) && php_sapi_name() === 'cli'); } /** * @brief show status message as text (CLI) or JSON-encoded array (web) * * @param array $statusarray associative array with type/message pairs * @return string */ function status($statusarray) { if (isCommandLineInterface()) { foreach ($statusarray as $status => $message) { echo $status . ":" . $message . "\n"; } } else { echo json_encode(array_map(function ($text) { return nl2br($text); }, $statusarray)); } } /** * @brief show status message and die * * @param array $statusarray associative array with type/message pairs */ function croak($statusarray) { status($statusarray); die; } function getSecondsTotalVideosLength() { $configFile = dirname(__FILE__) . '/../videos/configuration.php'; require_once $configFile; global $global; if (!User::isLogged()) { return 0; } $sql = "SELECT * FROM videos v "; $formats = ""; $values = array(); if (!User::isAdmin()) { $id = User::getId(); $sql .= " WHERE users_id = ? "; $formats = "i"; $values = array($id); } $res = sqlDAL::readSql($sql, $formats, $values); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $seconds = 0; foreach ($fullData as $row) { $seconds += parseDurationToSeconds($row['duration']); } return $seconds; } function getMinutesTotalVideosLength() { $seconds = getSecondsTotalVideosLength(); return floor($seconds / 60); } function secondsToVideoTime($seconds) { if (!is_numeric($seconds)) { return $seconds; } $seconds = round($seconds); $hours = floor($seconds / 3600); $mins = floor($seconds / 60 % 60); $secs = floor($seconds % 60); return sprintf('%02d:%02d:%02d', $hours, $mins, $secs); } function parseSecondsToDuration($seconds) { return secondsToVideoTime($seconds); } function parseDurationToSeconds($str) { if (is_numeric($str)) { return intval($str); } $durationParts = explode(":", $str); if (empty($durationParts[1]) || $durationParts[0] == "EE") { return 0; } if (empty($durationParts[2])) { $durationParts[2] = 0; } $minutes = intval(($durationParts[0]) * 60) + intval($durationParts[1]); return intval($durationParts[2]) + ($minutes * 60); } function durationToSeconds($str) { return parseDurationToSeconds($str); } function secondsToDuration($seconds) { return parseSecondsToDuration($seconds); } /** * * @global type $global * @param type $mail * call it before send mail to let AVideo decide the method */ function setSiteSendMessage(&$mail) { global $global; if (empty($_POST["comment"])) { $_POST["comment"] = ""; } require_once $global['systemRootPath'] . 'objects/configuration.php'; $config = new Configuration(); $mail->CharSet = 'UTF-8'; if ($config->getSmtp()) { _error_log("Sending SMTP Email"); $mail->CharSet = 'UTF-8'; $mail->IsSMTP(); // enable SMTP if (!empty($_POST) && $_POST["comment"] == "Teste of comment" && User::isAdmin()) { $mail->SMTPDebug = 3; $mail->Debugoutput = function ($str, $level) { _error_log("SMTP ERROR $level; message: $str", AVideoLog::$ERROR); }; } $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->SMTPAuth = $config->getSmtpAuth(); // authentication enabled $mail->SMTPSecure = $config->getSmtpSecure(); // secure transfer enabled REQUIRED for Gmail $mail->Host = $config->getSmtpHost(); $mail->Port = $config->getSmtpPort(); $mail->Username = $config->getSmtpUsername(); $mail->Password = $config->getSmtpPassword(); //_error_log(print_r($config, true)); } else { _error_log("Sending SendMail Email"); $mail->isSendmail(); } } function array_iunique($array) { return array_intersect_key($array, array_unique(array_map("strtolower", $array))); } function partition(array $list, $totalItens) { $listlen = count($list); _error_log("partition: listlen={$listlen} totalItens={$totalItens}"); $p = ceil($listlen / $totalItens); $partlen = floor($listlen / $p); $partition = array(); $mark = 0; for ($index = 0; $index < $p; $index++) { $partition[$index] = array_slice($list, $mark, $totalItens); $mark += $totalItens; } return $partition; } function sendSiteEmail($to, $subject, $message) { global $advancedCustom; if (empty($to)) { return false; } if (!is_array($to)) { $to = array($to); } if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); } $subject = UTF8encode($subject); $message = UTF8encode($message); $message = createEmailMessageFromTemplate($message); _error_log("sendSiteEmail [" . count($to) . "] {$subject}"); global $config, $global; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/PHPMailer.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/SMTP.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/Exception.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/PHPMailer.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/SMTP.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/Exception.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { if (!is_array($to)) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($to); $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } else { $size = intval(@$advancedCustom->splitBulkEmailSend); if (empty($size)) { $size = 90; } $to = array_iunique($to); $pieces = partition($to, $size); foreach ($pieces as $piece) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $count = 0; foreach ($piece as $value) { $count++; _error_log("sendSiteEmail::addBCC [{$count}] {$value}"); $mail->addBCC($value); } $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } } //Set the subject line return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function createEmailMessageFromTemplate($message) { //check if the message already have a HTML body if (preg_match("/html>/i", $message)) { return $message; } global $global, $config; $text = file_get_contents("{$global['systemRootPath']}view/include/emailTemplate.html"); $siteTitle = $config->getWebSiteTitle(); $logo = "getLogo(true) . "\" alt=\"{$siteTitle}\">"; $words = array($logo, $message, $siteTitle); $replace = array('{logo}', '{message}', '{siteTitle}'); return str_replace($replace, $words, $text); } function sendEmailToSiteOwner($subject, $message) { global $advancedCustom; $subject = UTF8encode($subject); $message = UTF8encode($message); _error_log("sendEmailToSiteOwner {$subject}"); global $config, $global; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/PHPMailer.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/SMTP.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/Exception.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/PHPMailer.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/SMTP.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/Exception.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($contactEmail); $resp = $mail->send(); if (!$resp) { _error_log("sendEmailToSiteOwner Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendEmailToSiteOwner Success Info: $subject " . json_encode($to)); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { //_error_log("parseVideos: $videoString"); if (strpos($videoString, 'youtube.com/embed') !== false) { return $videoString . (parse_url($videoString, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } if (strpos($videoString, 'iframe') !== false) { // retrieve the video url $anchorRegex = '/src="(.*)?"/isU'; $results = array(); if (preg_match($anchorRegex, $video, $results)) { $link = trim($results[1]); } } else { // we already have a url $link = $videoString; } if (stripos($link, 'embed') !== false) { return $link . (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtube.com') !== false) { preg_match( '/[\\?\\&]v=([^\\?\\&]+)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg if (empty($matches[1])) { return $link; } $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtu.be') !== false) { //https://youtu.be/9XXOBSsPoMU preg_match( '/youtu.be\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'player.vimeo.com') !== false) { // works on: // http://player.vimeo.com/video/37985580?title=0&byline=0&portrait=0 $videoIdRegex = '/player.vimeo.com\/video\/([0-9]+)\??/i'; preg_match($videoIdRegex, $link, $matches); $id = $matches[1]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com/channels') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/channels\/[a-z0-9-]+\/(\d+)($|\/)/i', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'dailymotion.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?dailymotion.com\/video\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//www.dailymotion.com/embed/video/' . $id; } elseif (strpos($link, 'metacafe.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?metacafe.com\/watch\/([a-zA-Z0-9_\/-]+)$/', $link, $matches ); $id = $matches[2]; return '//www.metacafe.com/embed/' . $id; } elseif (strpos($link, 'vid.me') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vid.me\/([a-zA-Z0-9_-]+)$/', $link, $matches ); $id = $matches[2]; return '//vid.me/e/' . $id; } elseif (strpos($link, 'rutube.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?rutube.ru\/video\/([a-zA-Z0-9_-]+)\/.*/', $link, $matches); $id = $matches[2]; return '//rutube.ru/play/embed/' . $id; } elseif (strpos($link, 'ok.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?ok.ru\/video\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//ok.ru/videoembed/' . $id; } elseif (strpos($link, 'streamable.com') !== false) { //extract the ID preg_match('/\/\/(www\.)?streamable.com\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//streamable.com/s/' . $id; } elseif (strpos($link, 'twitch.tv/videos') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/videos\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[2])) { $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '#'; } //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/[a-zA-Z0-9_-]+\/v\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '#'; } elseif (strpos($link, 'twitch.tv') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?channel=' . $id . '#'; } elseif (strpos($link, '/evideo/') !== false) { //extract the ID preg_match('/(http.+)\/evideo\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site $site = $matches[1]; $id = $matches[2]; return $site . '/evideoEmbed/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } elseif (strpos($link, '/video/') !== false) { //extract the ID preg_match('/(http.+)\/video\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site if (!empty($matches[1])) { $site = $matches[1]; $id = $matches[2]; return $site . '/videoEmbeded/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } else { return $link; } } $url = $videoString; $url_parsed = parse_url($url); if (empty($url_parsed['query'])) { return ""; } $new_qs_parsed = array(); // Grab our first query string parse_str($url_parsed['query'], $new_qs_parsed); // Here's the other query string $other_query_string = 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; $other_qs_parsed = array(); parse_str($other_query_string, $other_qs_parsed); // Stitch the two query strings together $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); $final_query_string = http_build_query($final_query_string_array); // Now, our final URL: $new_url = $url_parsed['scheme'] . '://' . $url_parsed['host'] . $url_parsed['path'] . '?' . $final_query_string; return $new_url; // return data } $canUseCDN = array(); function canUseCDN($videos_id) { if (empty($videos_id)) { return false; } global $global, $canUseCDN; if (!isset($canUseCDN[$videos_id])) { require_once $global['systemRootPath'] . 'plugin/VR360/Objects/VideosVR360.php'; $pvr360 = AVideoPlugin::isEnabledByName('VR360'); // if the VR360 is enabled you can not use the CDN, it fail to load the GL $isVR360Enabled = VideosVR360::isVR360Enabled($videos_id); if ($pvr360 && $isVR360Enabled) { $ret = false; } else { $ret = true; } //_error_log(json_encode(array('canUseCDN'=>$ret, '$pvr360'=>$pvr360, '$isVR360Enabled'=>$isVR360Enabled, '$videos_id'=>$videos_id))); $canUseCDN[$videos_id] = $ret; } return $canUseCDN[$videos_id]; } function clearVideosURL($fileName = "") { global $global; $path = getCacheDir() . "getVideosURL/"; if (empty($path)) { rrmdir($path); } else { $cacheFilename = "{$path}{$fileName}.cache"; @unlink($cacheFilename); } } function maxLifetime() { global $maxLifetime; if (!isset($maxLifetime)) { $aws_s3 = AVideoPlugin::getObjectDataIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::getObjectDataIfEnabled('Blackblaze_B2'); $secure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); $maxLifetime = 0; if (!empty($aws_s3) && !empty($aws_s3->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $aws_s3->presignedRequestSecondsTimeout < $maxLifetime) ){ $maxLifetime = $aws_s3->presignedRequestSecondsTimeout; _error_log("maxLifetime: AWS_S3 = {$maxLifetime}"); } if (!empty($bb_b2) && !empty($aws_s3->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $bb_b2->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $bb_b2->presignedRequestSecondsTimeout; _error_log("maxLifetime: B2 = {$maxLifetime}"); } if (!empty($secure) && !empty($aws_s3->tokenTimeOut) && (empty($maxLifetime) || $secure->tokenTimeOut < $maxLifetime)) { $maxLifetime = $secure->tokenTimeOut; _error_log("maxLifetime: Secure = {$maxLifetime}"); } } return $maxLifetime; } $cacheExpirationTime = false; function cacheExpirationTime() { if (isBot()) { return 604800; // 1 week } global $cacheExpirationTime; if (empty($cacheExpirationTime)) { $obj = AVideoPlugin::getObjectDataIfEnabled('Cache'); $cacheExpirationTime = @$obj->cacheTimeInSeconds; } return intval($cacheExpirationTime); } /** * tell if a file should recreate a cache, based on its time and the plugins toke expirations * @param type $filename * @return boolean */ function recreateCache($filename) { return (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()); } function _getImagesURL($fileName, $type) { global $global; $files = array(); $source = Video::getSourceFile($fileName, ".jpg"); $file = $source['path']; if (file_exists($file)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["jpg"] = array( 'filename' => "{$type}.png", 'path' => "{$global['systemRootPath']}view/img/{$type}.png", 'url' => "{$global['webSiteRootURL']}view/img/{$type}.png", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file = $source['path']; if (file_exists($file)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } elseif ($type != 'image') { $files["pjpg"] = array( 'filename' => "{$type}_portrait.png", 'path' => "{$global['systemRootPath']}view/img/{$type}_portrait.png", 'url' => "{$global['webSiteRootURL']}view/img/{$type}_portrait.png", 'type' => 'image', ); } return $files; } function getVideosURLPDF($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".pdf"); $file = $source['path']; $files["pdf"] = array( 'filename' => "{$fileName}.pdf", 'path' => $file, 'url' => $source['url'], 'type' => 'pdf', ); $files = array_merge($files, _getImagesURL($fileName, 'pdf')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLIMAGE($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('png', 'gif', 'webp', 'jpg'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["image"] = array( 'filename' => "{$fileName}.{$value}", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'image')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLZIP($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('zip'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["zip"] = array( 'filename' => "{$fileName}.zip", 'path' => $file, 'url' => $source['url'], 'type' => 'zip', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'zip')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLArticle($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; //$files = array_merge($files, _getImagesURL($fileName, 'article')); $files = _getImagesURL($fileName, 'article'); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLAudio($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".mp3"); $file = $source['path']; $files["mp3"] = array( 'filename' => "{$fileName}.mp3", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); $files = array_merge($files, _getImagesURL($fileName, 'audio_wave')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLAudio generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURL($fileName, $cache = true) { return getVideosURL_V2($fileName); // disable this function soon } function getVideosURLMP4Only($fileName) { $allFiles = getVideosURL_V2($fileName); if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'mp4') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return array(); } function getVideosURLWEBMOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'webm') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return array(); } function getVideosURLMP4WEBMOnly($fileName) { return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName)); } function getVideosURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video') { unset($allFiles[$key]); } } return $allFiles; } $getVideosURL_V2Array = array(); function getVideosURL_V2($fileName, $recreateCache = false) { global $global, $getVideosURL_V2Array; if (empty($fileName)) { return array(); } //$recreateCache = true; $cleanfilename = Video::getCleanFilenameFromFile($fileName); if (!empty($getVideosURL_V2Array[$cleanfilename])) { return $getVideosURL_V2Array[$cleanfilename]; } $pdf = "{$global['systemRootPath']}videos/{$cleanfilename}.pdf"; $mp3 = "{$global['systemRootPath']}videos/{$cleanfilename}.mp3"; if (file_exists($pdf)) { return getVideosURLPDF($fileName); } elseif (file_exists($mp3)) { return getVideosURLAudio($fileName); } $cacheName = "getVideosURL_V2$fileName"; if (empty($recreateCache)) { $lifetime = maxLifetime(); $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; TimeLogStart($TimeLog1); $files = object_to_array(ObjectYPT::getCache($cacheName, $lifetime, true)); if (is_array($files)) { //_error_log("getVideosURL_V2: do NOT recreate lifetime = {$lifetime}"); $preg_match_url = addcslashes($global['webSiteRootURL'], "/") . "videos"; foreach ($files as $value) { // check if is a dummy file and the URL still wrong if ( $value['type'] === 'video' && // is a video preg_match("/^{$preg_match_url}/", $value['url']) && // the URL is the same as the main domain filesize($value['path']) < 20) { // file size is small _error_log("getVideosURL_V2:: dummy file found, fix cache " . json_encode(array("/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), filesize($value['path']), $value))); unset($files); break; } else { //_error_log("getVideosURL_V2:: NOT dummy file ". json_encode(array("/^{$preg_match_url}video/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']),filesize($value['path']),$value))); } } //_error_log("getVideosURL_V2:: cachestill good ". json_encode($files)); } else { //_error_log("getVideosURL_V2:: cache not found ". json_encode($files)); } TimeLogEnd($TimeLog1, __LINE__); } else { _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace())); } if (empty($files)) { $files = array(); $plugin = AVideoPlugin::loadPlugin("VideoHLS"); if (!empty($plugin)) { $files = VideoHLS::getSourceFile($fileName); } $video = array('webm', 'mp4'); $audio = array('mp3', 'ogg'); $image = array('jpg', 'gif', 'webp'); $formats = array_merge($video, $audio, $image); //$globQuery = "{$global['systemRootPath']}videos/{$cleanfilename}*.{" . implode(",", $formats) . "}"; //$filesInDir = glob($globQuery, GLOB_BRACE); $filesInDir = globVideosDir($cleanfilename, true); foreach ($filesInDir as $file) { $parts = pathinfo($file); $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); if (empty($source)) { continue; } if (filesize($file) < 20000 && !preg_match("/Dummy File/i", file_get_contents($file))) { continue; } if (preg_match("/{$cleanfilename}(_.+)[.]{$parts['extension']}$/", $file, $matches)) { $resolution = $matches[1]; } else { preg_match('/_([^_]{0,4}).' . $parts['extension'] . '$/', $file, $matches); $resolution = @$matches[1]; } $type = 'video'; if (in_array($parts['extension'], $video)) { $type = 'video'; } elseif (in_array($parts['extension'], $audio)) { $type = 'audio'; } elseif (in_array($parts['extension'], $image)) { $type = 'image'; } $files["{$parts['extension']}{$resolution}"] = array( 'filename' => "{$parts['filename']}.{$parts['extension']}", 'path' => $file, 'url' => $source['url'], 'type' => $type, 'format' => strtolower($parts['extension']), ); } ObjectYPT::setCache($cacheName, $files); } $getVideosURL_V2Array[$cleanfilename] = $files; return $getVideosURL_V2Array[$cleanfilename]; } function getSources($fileName, $returnArray = false, $try = 0) { if ($returnArray) { $videoSources = $audioTracks = $subtitleTracks = array(); } else { $videoSources = $audioTracks = $subtitleTracks = ""; } $video = Video::getVideoFromFileNameLight($fileName); if ($video['type'] !== 'audio' && function_exists('getVRSSources')) { $videoSources = getVRSSources($fileName, $returnArray); } else { //$files = getVideosURL($fileName); $files = getVideosURL_V2($fileName, !empty($try)); $sources = ""; $sourcesArray = array(); foreach ($files as $key => $value) { $path_parts = pathinfo($value['path']); if ($path_parts['extension'] == "webm" || $path_parts['extension'] == "mp4" || $path_parts['extension'] == "m3u8" || $path_parts['extension'] == "mp3" || $path_parts['extension'] == "ogg") { $obj = new stdClass(); $obj->type = mime_content_type_per_filename($value['path']); $sources .= "type}\">"; $obj->src = $value['url']; $sourcesArray[] = $obj; } } $videoSources = $returnArray ? $sourcesArray : $sources; } if (function_exists('getVTTTracks')) { $subtitleTracks = getVTTTracks($fileName, $returnArray); } if ($returnArray) { $return = array_merge($videoSources, $audioTracks, $subtitleTracks); } else { $return = $videoSources . $audioTracks . $subtitleTracks; } $obj = new stdClass(); $obj->result = $return; if (empty($videoSources) && empty($audioTracks) && !empty($video['id']) && $video['type'] == 'video') { if (empty($try)) { //sleep(1); $sources = getSources($fileName, $returnArray, $try + 1); if (!empty($sources)) { Video::updateFilesize($video['id']); } Video::clearCache($video['id']); return $sources; } else { _error_log("getSources($fileName) File not found " . json_encode($video)); $obj = new stdClass(); $obj->type = "video/mp4"; $obj->src = "Video not found"; $obj->label = "Video not found"; $obj->res = 0; $sourcesArray["mp4"] = $obj; $sources["mp4"] = "type}\" label=\"{$obj->label}\" res=\"{$obj->res}\">"; $return = $returnArray ? $sourcesArray : implode(PHP_EOL, $sources); } } return $return; } /** * * @param type $file_src * @return typeget image size with cache */ function getimgsize($file_src) { global $_getimagesize; if (empty($_getimagesize)) { $_getimagesize = array(); } $name = "getimgsize_" . md5($file_src); if (!empty($_getimagesize[$name])) { $size = $_getimagesize[$name]; } else { $cached = ObjectYPT::getCache($name, 86400); //one day if (!empty($cached)) { $c = (Array) $cached; $size = array(); foreach ($c as $key => $value) { if (preg_match("/^[0-9]+$/", $key)) { $key = intval($key); } $size[$key] = $value; } $_getimagesize[$name] = $size; return $size; } $size = @getimagesize($file_src); if (empty($size)) { $size = array(1024, 768); } ObjectYPT::setCache($name, $size); $_getimagesize[$name] = $size; } return $size; } function im_resize($file_src, $file_dest, $wd, $hd, $q = 80) { if (empty($file_dest)) { return false; } if (!file_exists($file_src)) { _error_log("im_resize: Source not found: {$file_src}"); return false; } $size = getimgsize($file_src); if ($size === false) { _error_log("im_resize: Could not get image size: {$file_src}"); return false; } if (empty($size['mime']) || $size['mime'] == 'image/pjpeg') { $size['mime'] = 'image/jpeg'; } $format = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1)); if (empty($format)) { $format = 'jpeg'; } $destformat = strtolower(substr($file_dest, -4)); if (empty($destformat)) { _error_log("destformat not found {$file_dest}"); $destformat = ".jpg"; } $icfunc = "imagecreatefrom" . $format; if (!function_exists($icfunc)) { _error_log("im_resize: Function does not exists: {$icfunc}"); return false; } $imgSize = getimagesize($file_src); if (empty($imgSize)) { _error_log("im_resize: getimagesize($file_src) return false " . json_encode($imgSize)); return false; } try { $src = $icfunc($file_src); } catch (Exception $exc) { _error_log("im_resize: " . $exc->getMessage()); _error_log("im_resize: Try {$icfunc} from string"); $src = imagecreatefromstring(file_get_contents($file_src)); if (!$src) { _error_log("im_resize: fail {$icfunc} from string"); return false; } } $ws = imagesx($src); $hs = imagesy($src); if ($ws <= $hs) { $hd = ceil(($wd * $hs) / $ws); } else { $wd = ceil(($hd * $ws) / $hs); } if ($ws <= $wd) { $wd = $ws; $hd = $hs; } $wc = ($wd * $hs) / $hd; if ($wc <= $ws) { $hc = ($wc * $hd) / $wd; } else { $hc = ($ws * $hd) / $wd; $wc = ($wd * $hc) / $hd; } $dest = imagecreatetruecolor($wd, $hd); switch ($format) { case "png": imagealphablending($dest, false); imagesavealpha($dest, true); $transparent = imagecolorallocatealpha($dest, 255, 255, 255, 127); imagefilledrectangle($dest, 0, 0, $wd, $hd, $transparent); break; case "gif": // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($src, 0, 0, 0); // removing the black from the placeholder imagecolortransparent($src, $background); break; } imagecopyresampled($dest, $src, 0, 0, ($ws - $wc) / 2, ($hs - $hc) / 2, $wd, $hd, $wc, $hc); $saved = false; if ($destformat == '.png') { $saved = imagepng($dest, $file_dest); } if ($destformat == '.jpg') { $saved = imagejpeg($dest, $file_dest, $q); } if (!$saved) { _error_log('saving failed'); } imagedestroy($dest); imagedestroy($src); @chmod($file_dest, 0666); return true; } function im_resizeV2($file_src, $file_dest, $wd, $hd, $q = 80) { _error_log("im_resizeV2: $file_src, $file_dest, $wd, $hd, $q"); $newImage = im_resize($file_src, $file_dest, $wd, $hd, 100); if (!$newImage) { return false; } $src = imagecreatefromjpeg($file_dest); $ws = imagesx($src); $hs = imagesy($src); if ($ws < $wd) { $dst_x = ($wd - $ws) / 2; } else { $dst_x = 0; } if ($hs < $hd) { $dst_y = ($hd - $hs) / 2; } else { $dst_y = 0; } $mapImage = imagecreatetruecolor($wd, $hd); $bgColor = imagecolorallocate($mapImage, 0, 0, 0); imagefill($mapImage, 0, 0, $bgColor); $tileImg = imagecreatefromjpeg($file_dest); imagecopy($mapImage, $tileImg, $dst_x, $dst_y, 0, 0, $ws, $hs); $saved = imagejpeg($mapImage, $file_dest, $q); return $saved; } function im_resizeV3($file_src, $file_dest, $wd, $hd) { _error_log("im_resizeV3: $file_src, $file_dest, $wd, $hd"); // This tries to preserve the aspect ratio of the thumb while letterboxing it in // The same way that the encoder now does. eval('$ffmpeg ="ffmpeg -i {$file_src} -filter_complex \"scale=(iw*sar)*min({$wd}/(iw*sar)\,{$hd}/ih):ih*min({$wd}/(iw*sar)\,{$hd}/ih), pad={$wd}:{$hd}:({$wd}-iw*min({$wd}/iw\,{$hd}/ih))/2:({$hd}-ih*min({$wd}/iw\,{$hd}/ih))/2\" -sws_flags lanczos -qscale:v 2 {$file_dest}";'); exec($ffmpeg . " < /dev/null 2>&1", $output, $return_val); } function im_resize_max_size($file_src, $file_dest, $max_width, $max_height) { $fn = $file_src; $tmpFile = getTmpFile() . ".jpg"; if (empty($fn)) { _error_log("im_resize_max_size: file name is empty, Destination: {$file_dest}", AVideoLog::$ERROR); return false; } if (function_exists("exif_read_data")) { error_log($fn); convertImage($fn, $tmpFile, 100); $exif = exif_read_data($tmpFile); if ($exif && isset($exif['Orientation'])) { $orientation = $exif['Orientation']; if ($orientation != 1) { $img = imagecreatefromjpeg($tmpFile); $deg = 0; switch ($orientation) { case 3: $deg = 180; break; case 6: $deg = 270; break; case 8: $deg = 90; break; } if ($deg) { $img = imagerotate($img, $deg, 0); } imagejpeg($img, $fn, 100); } } } else { _error_log("Make sure you install the php_mbstring and php_exif to be able to rotate images"); } $size = getimagesize($fn); $ratio = $size[0] / $size[1]; // width/height if ($size[0] <= $max_width && $size[1] <= $max_height) { $width = $size[0]; $height = $size[1]; } elseif ($ratio > 1) { $width = $max_width; $height = $max_height / $ratio; } else { $width = $max_width * $ratio; $height = $max_height; } $src = imagecreatefromstring(file_get_contents($fn)); $dst = imagecreatetruecolor($width, $height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); imagedestroy($src); imagejpeg($dst, $file_dest); // adjust format as needed imagedestroy($dst); @unlink($file_src); @unlink($tmpFile); } function convertImage($originalImage, $outputImage, $quality) { $imagetype = 0; if (function_exists('exif_imagetype')) { $imagetype = exif_imagetype($originalImage); } // jpg, png, gif or bmp? $exploded = explode('.', $originalImage); $ext = $exploded[count($exploded) - 1]; try { if ($imagetype == IMAGETYPE_JPEG || preg_match('/jpg|jpeg/i', $ext)) { $imageTmp = @imagecreatefromjpeg($originalImage); } elseif ($imagetype == IMAGETYPE_PNG || preg_match('/png/i', $ext)) { $imageTmp = imagecreatefrompng($originalImage); } elseif ($imagetype == IMAGETYPE_GIF || preg_match('/gif/i', $ext)) { $imageTmp = imagecreatefromgif($originalImage); } elseif ($imagetype == IMAGETYPE_BMP || preg_match('/bmp/i', $ext)) { $imageTmp = imagecreatefrombmp($originalImage); } elseif ($imagetype == IMAGETYPE_WEBP || preg_match('/webp/i', $ext)) { $imageTmp = imagecreatefromwebp($originalImage); } else { _error_log("convertImage: File Extension not found ($originalImage, $outputImage, $quality) " . exif_imagetype($originalImage)); return 0; } } catch (Exception $exc) { _error_log("convertImage: " . $exc->getMessage()); return 0; } if (!is_resource($imageTmp)) { _error_log("convertImage: could not create a resource $originalImage, $outputImage, $quality"); return 0; } // quality is a value from 0 (worst) to 100 (best) imagejpeg($imageTmp, $outputImage, $quality); imagedestroy($imageTmp); return 1; } function decideMoveUploadedToVideos($tmp_name, $filename, $type = "video") { global $global; $obj = new stdClass(); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); $destinationFile = "{$global['systemRootPath']}videos/{$filename}"; _error_log("decideMoveUploadedToVideos: {$filename}"); $path_info = pathinfo($filename); if ($type !== "zip" && $path_info['extension'] === 'zip') { _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); $dir = "{$global['systemRootPath']}videos/{$path_info['filename']}"; unzipDirectory($tmp_name, $dir); // unzip it cleanDirectory($dir); if (!empty($aws_s3)) { //$aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { $bb_b2->move_uploaded_directory($dir); } elseif (!empty($ftp)) { //$ftp->move_uploaded_file($tmp_name, $filename); } } else { _error_log("decideMoveUploadedToVideos: NOT ZIp file {$filename}"); if (!empty($aws_s3)) { _error_log("decideMoveUploadedToVideos: S3 {$filename}"); $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { _error_log("decideMoveUploadedToVideos: B2 {$filename}"); $bb_b2->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { _error_log("decideMoveUploadedToVideos: FTP {$filename}"); $ftp->move_uploaded_file($tmp_name, $filename); } else { _error_log("decideMoveUploadedToVideos: Local {$filename}"); if (!move_uploaded_file($tmp_name, $destinationFile)) { if (!rename($tmp_name, $destinationFile)) { if (!copy($tmp_name, $destinationFile)) { $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, $destinationFile)"; die(json_encode($obj)); } } } chmod($destinationFile, 0644); } } sleep(1); $fsize = @filesize($destinationFile); _error_log("decideMoveUploadedToVideos: destinationFile {$destinationFile} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")"); Video::clearCacheFromFilename($filename); } function unzipDirectory($filename, $destination) { global $global; // Wait a couple of seconds to make sure the file has completed transfer sleep(2); ini_set('memory_limit', '-1'); ini_set('max_execution_time', 7200); // 2 hours $cmd = "unzip {$filename} -d {$destination}" . " 2>&1"; _error_log("unzipDirectory: {$cmd}"); exec($cmd, $output, $return_val); if ($return_val !== 0 && function_exists("zip_open")) { // try to unzip using PHP _error_log("unzipDirectory: TRY to use PHP {$filename}"); $zip = zip_open($filename); if ($zip) { while ($zip_entry = zip_read($zip)) { $path = "{$destination}/" . zip_entry_name($zip_entry); _error_log("unzipDirectory: fopen $path"); if (substr(zip_entry_name($zip_entry), -1) == '/') { make_path($path); } else { make_path($path); $fp = fopen($path, "w"); if (zip_entry_open($zip, $zip_entry, "r")) { $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); fwrite($fp, "$buf"); zip_entry_close($zip_entry); fclose($fp); } } } zip_close($zip); } else { _error_log("unzipDirectory: ERROR php zip does not work"); } } else { _error_log("unzipDirectory: Success {$destination}"); } @unlink($filename); } function make_path($path) { if (substr($path, -1) !== '/') { $path = pathinfo($path, PATHINFO_DIRNAME); } if (!is_dir($path)) { @mkdir($path, 0755, true); } } /** * for security clean all non secure files from directory * @param type $dir * @param type $allowedExtensions * @return type */ function cleanDirectory($dir, $allowedExtensions = array('key', 'm3u8', 'ts', 'vtt', 'jpg', 'gif', 'mp3', 'webm')) { $ffs = scandir($dir); unset($ffs[array_search('.', $ffs, true)]); unset($ffs[array_search('..', $ffs, true)]); // prevent empty ordered elements if (count($ffs) < 1) { return; } foreach ($ffs as $ff) { $current = $dir . '/' . $ff; if (is_dir($current)) { cleanDirectory($current, $allowedExtensions); } $path_parts = pathinfo($current); if (!empty($path_parts['extension']) && !in_array($path_parts['extension'], $allowedExtensions)) { unlink($current); } } } function decideFile_put_contentsToVideos($tmp_name, $filename) { global $global; $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); if (!empty($bb_b2)) { $bb_b2->move_uploaded_file($tmp_name, $filename); } elseif (!empty($aws_s3)) { $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { $ftp->move_uploaded_file($tmp_name, $filename); } else { if (!move_uploaded_file($tmp_name, "{$global['systemRootPath']}videos/{$filename}")) { $obj->msg = "Error on move_uploaded_file({$tmp_name}, {$global['systemRootPath']}videos/{$filename})"; die(json_encode($obj)); } } } if (!function_exists('mime_content_type')) { function mime_content_type($filename) { return mime_content_type_per_filename($filename); } } function fontAwesomeClassName($filename) { $mime_type = mime_content_type_per_filename($filename); // List of official MIME Types: http://www.iana.org/assignments/media-types/media-types.xhtml $icon_classes = array( // Media 'image' => 'fas fa-file-image', 'audio' => 'fas fa-file-audio', 'video' => 'fas fa-file-video', // Documents 'application/pdf' => 'fas fa-file-pdf', 'application/msword' => 'fas fa-file-word', 'application/vnd.ms-word' => 'fas fa-file-word', 'application/vnd.oasis.opendocument.text' => 'fas fa-file-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fas fa-file-word', 'application/vnd.ms-excel' => 'fas fa-file-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fas fa-file-excel', 'application/vnd.oasis.opendocument.spreadsheet' => 'fas fa-file-excel', 'application/vnd.ms-powerpoint' => 'fas fa-file-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml' => 'fas fa-file-powerpoint', 'application/vnd.oasis.opendocument.presentation' => 'fas fa-file-powerpoint', 'text/plain' => 'far fa-file-alt', 'text/html' => 'fas fa-code', 'application/json' => 'fas fa-code', // Archives 'application/gzip' => 'far fa-file-archive', 'application/zip' => 'far fa-file-archive', ); foreach ($icon_classes as $text => $icon) { if (strpos($mime_type, $text) === 0) { return $icon; } } return 'fas fa-file'; } function mime_content_type_per_filename($filename) { $mime_types = array( 'txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', // images 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', // archives 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', // audio/video 'mp3' => 'audio/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'mp4' => 'video/mp4', 'avi' => 'video/avi', 'mkv' => 'video/mkv', 'wav' => 'audio/wav', 'm4v' => 'video/mpeg', 'webm' => 'video/webm', 'wmv' => 'video/wmv', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'f4v' => 'video/x-flv', 'm4v' => 'video/m4v', 'm4a' => 'video/quicktime', 'm2p' => 'video/quicktime', 'rm' => 'video/quicktime', 'vob' => 'video/quicktime', 'mkv' => 'video/quicktime', '3gp' => 'video/quicktime', 'm3u8' => 'application/x-mpegURL', // adobe 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', // ms office 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', // open office 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet' ); if (filter_var($filename, FILTER_VALIDATE_URL) === false) { $ext = pathinfo($filename, PATHINFO_EXTENSION); } else { $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION); } if ($ext === 'mp4' || $ext === 'webm') { $securePlugin = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); if (!empty($securePlugin)) { if (method_exists($securePlugin, "useEncoderWatrermarkFromFileName") && $securePlugin->useEncoderWatrermarkFromFileName($filename)) { return "application/x-mpegURL"; } } } if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } elseif (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $filename); finfo_close($finfo); return $mimetype; } else { return 'application/octet-stream'; } } function combineFiles($filesArray, $extension = "js") { global $global, $advancedCustom; $cacheDir = $global['systemRootPath'] . 'videos/cache/' . $extension . "/"; if (!is_dir($cacheDir)) { mkdir($cacheDir, 0777, true); } $str = ""; $fileName = ""; foreach ($filesArray as $value) { $fileName .= $value; } if ($advancedCustom != false) { $minifyEnabled = $advancedCustom->EnableMinifyJS; } else { $minifyEnabled = false; } // temporary disable minify $minifyEnabled = false; $md5FileName = md5($fileName) . ".{$extension}"; if (!file_exists($cacheDir . $md5FileName)) { foreach ($filesArray as $value) { if (file_exists($global['systemRootPath'] . $value)) { $str .= "\n/*{$value} created local with systemRootPath */\n" . local_get_contents($global['systemRootPath'] . $value); } elseif (file_exists($value)) { $str .= "\n/*{$value} created local with full-path given */\n" . local_get_contents($value); } else { $allowed = ""; if (ini_get('allow_url_fopen')) { $allowed .= "allow_url_fopen is on and "; } if (function_exists('curl_init')) { $allowed .= "curl is on"; } else { $allowed .= "curl is off"; } $content = url_get_contents($value); if (empty($content)) { $allowed .= " - web-fallback 1 (add webSiteRootURL)"; $content = url_get_contents($global['webSiteRootURL'] . $value); } $str .= "\n/*{$value} created via web with own url ({$allowed}) */\n" . $content; } } //if ((($extension == "js" || $extension == "css") && ($minifyEnabled))) { if ($extension == "css" && ($minifyEnabled)) { require_once $global['systemRootPath'] . 'objects/jshrink.php'; $str = \JShrink\Minifier::minify($str, array('flaggedComments' => false)); } file_put_contents($cacheDir . $md5FileName, $str); } return $global['webSiteRootURL'] . 'videos/cache/' . $extension . "/" . $md5FileName . "?" . filectime($cacheDir . $md5FileName); } function local_get_contents($path) { if (function_exists('fopen')) { $myfile = fopen($path, "r") or die("Unable to open file!"); $text = fread($myfile, filesize($path)); fclose($myfile); return $text; } } function getSelfUserAgent() { global $global, $AVideoStreamer_UA; $agent = $AVideoStreamer_UA . " "; $agent .= parse_url($global['webSiteRootURL'], PHP_URL_HOST); return $agent; } function url_get_contents($url, $ctx = "", $timeout = 0, $debug = false) { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if ($debug) { _error_log("url_get_contents: Start $url, $ctx, $timeout"); } $agent = getSelfUserAgent(); if (empty($ctx)) { $opts = array( 'http' => array('header' => "User-Agent: {$agent}\r\n"), "ssl" => array( "verify_peer" => false, "verify_peer_name" => false, "allow_self_signed" => true, ), ); if (!empty($timeout)) { ini_set('default_socket_timeout', $timeout); $opts['http'] = array('timeout' => $timeout); } $context = stream_context_create($opts); } else { $context = $ctx; } if (ini_get('allow_url_fopen')) { if ($debug) { _error_log("url_get_contents: allow_url_fopen {$url}"); } try { $tmp = @file_get_contents($url, false, $context); if ($tmp != false) { if ($debug) { _error_log("url_get_contents: SUCCESS file_get_contents($url) "); } return remove_utf8_bom($tmp); } if ($debug) { _error_log("url_get_contents: ERROR file_get_contents($url) "); } } catch (ErrorException $e) { if ($debug) { _error_log("url_get_contents: allow_url_fopen ERROR " . $e->getMessage() . " {$url}"); } return "url_get_contents: " . $e->getMessage(); } } elseif (function_exists('curl_init')) { if ($debug) { _error_log("url_get_contents: CURL {$url} "); } $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); if (!empty($timeout)) { curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout + 10); } $output = curl_exec($ch); curl_close($ch); if ($debug) { _error_log("url_get_contents: CURL SUCCESS {$url}"); } return remove_utf8_bom($output); } if ($debug) { _error_log("url_get_contents: Nothing yet {$url}"); } // try wget $filename = getTmpDir("YPTurl_get_contents") . md5($url); if ($debug) { _error_log("url_get_contents: try wget $filename {$url}"); } if (wget($url, $filename, $debug)) { if ($debug) { _error_log("url_get_contents: wget success {$url} "); } $result = file_get_contents($filename); unlink($filename); if (!empty($result)) { return remove_utf8_bom($result); } } elseif ($debug) { _error_log("url_get_contents: try wget fail {$url}"); } $result = @file_get_contents($url, false, $context); if ($debug) { _error_log("url_get_contents: Last try {$url}"); } return remove_utf8_bom($result); } function getUpdatesFilesArray() { global $config, $global; if (!class_exists('User') || !User::isAdmin()) { return array(); } $files1 = scandir($global['systemRootPath'] . "updatedb"); $updateFiles = array(); foreach ($files1 as $value) { preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); if (!empty($match)) { if ($config->currentVersionLowerThen($match[1])) { $updateFiles[] = array('filename' => $match[0], 'version' => $match[1]); } } } return $updateFiles; } function thereIsAnyUpdate() { if (!User::isAdmin()) { return false; } $name = 'thereIsAnyUpdate'; if (!isset($_SESSION['user'][$name])) { _session_start(); $_SESSION['user'][$name] = !empty(getUpdatesFilesArray()); } return $_SESSION['user'][$name]; } function thereIsAnyRemoteUpdate() { if (!User::isAdmin()) { return false; } global $config; $version = json_decode(url_get_contents("https://tutorials.avideo.com/version")); $name = 'thereIsAnyRemoteUpdate'; if (!isset($_SESSION['user'][$name])) { if (!empty($version)) { _session_start(); if (version_compare($config->getVersion(), $version->version) === -1) { $_SESSION['user'][$name] = $version; } else { $_SESSION['user'][$name] = false; } } } return $_SESSION['user'][$name]; } function UTF8encode($data) { global $advancedCustom, $global; if (!empty($advancedCustom->utf8Encode)) { return utf8_encode($data); } if (!empty($advancedCustom->utf8Decode)) { return utf8_decode($data); } return $data; } //detect search engine bots function isBot() { if (empty($_SERVER['HTTP_USER_AGENT'])) { return true; } if (isAVideoEncoder()) { return false; } // User lowercase string for comparison. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']); // A list of some common words used only for bots and crawlers. $bot_identifiers = array( 'bot', 'slurp', 'crawler', 'spider', 'curl', 'facebook', 'fetch', 'loader', ); // See if one of the identifiers is in the UA string. foreach ($bot_identifiers as $identifier) { if (strpos($user_agent, $identifier) !== false) { return true; } } return false; } /** * A function that could get me the last N lines of a log file. * @param type $filepath * @param type $lines * @param type $adaptive * @return boolean */ function tail($filepath, $lines = 1, $adaptive = true, $returnArray = false) { if (!function_exists('mb_strlen')) { $msg = "AVideoLog::ERROR you need to install the mb_strlen function to make it work, please the command 'sudo apt install php-mbstring'"; if ($returnArray) { return array(array($msg)); } else { return $msg; } } // Open file $f = @fopen($filepath, "rb"); if ($f === false) { return false; } // Sets buffer size, according to the number of lines to retrieve. // This gives a performance boost when reading a few lines from the file. if (!$adaptive) { $buffer = 4096; } else { $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096)); } // Jump to last character fseek($f, -1, SEEK_END); // Read it and adjust line number if necessary // (Otherwise the result would be wrong if file doesn't end with a blank line) if (fread($f, 1) != "\n") { $lines -= 1; } // Start reading $output = ''; $chunk = ''; // While we would like more while (ftell($f) > 0 && $lines >= 0) { // Figure out how far back we should jump $seek = min(ftell($f), $buffer); // Do the jump (backwards, relative to where we are) fseek($f, -$seek, SEEK_CUR); // Read a chunk and prepend it to our output $output = ($chunk = fread($f, $seek)) . $output; // Jump back to where we started reading fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR); // Decrease our line counter $lines -= substr_count($chunk, "\n"); } // While we have too many lines // (Because of buffer size we might have read too many) while ($lines++ < 0) { // Find first newline and remove all text before that $output = substr($output, strpos($output, "\n") + 1); } // Close file and return fclose($f); $output = trim($output); if ($returnArray) { $array = explode("\n", $output); $newArray = array(); foreach ($array as $value) { $newArray[] = array($value); } return $newArray; } else { return $output; } } function encryptPassword($password, $noSalt = false) { global $advancedCustom, $global, $advancedCustomUser; if (!empty($advancedCustomUser->encryptPasswordsWithSalt) && !empty($global['salt']) && empty($noSalt)) { $password .= $global['salt']; } return md5(hash("whirlpool", sha1($password))); } function encryptPasswordVerify($password, $hash, $encodedPass = false) { global $advancedCustom, $global; if (!$encodedPass || $encodedPass === 'false') { //_error_log("encryptPasswordVerify: encrypt"); $passwordSalted = encryptPassword($password); // in case you enable the salt later $passwordUnSalted = encryptPassword($password, true); } else { //_error_log("encryptPasswordVerify: do not encrypt"); $passwordSalted = $password; // in case you enable the salt later $passwordUnSalted = $password; } //_error_log("passwordSalted = $passwordSalted, hash=$hash, passwordUnSalted=$passwordUnSalted"); return $passwordSalted === $hash || $passwordUnSalted === $hash || $password === $hash; } function isMobile() { if (empty($_SERVER["HTTP_USER_AGENT"])) { return false; } global $global; require_once $global['systemRootPath'] . 'objects/Mobile_Detect.php'; $detect = new Mobile_Detect; return $detect->isMobile(); } function isAVideoMobileApp($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoMobileAPP_UA; if (preg_match("/{$AVideoMobileAPP_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoEncoder($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoEncoder_UA; if (preg_match("/{$AVideoEncoder_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideo($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoEncoder_UA; if (preg_match("/AVideo(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoEncoderOnSameDomain() { $url = isAVideoEncoder(); if (empty($url)) { return false; } $url = "http://{$url}"; return isSameDomainAsMyAVideo($url); } function isSameDomainAsMyAVideo($url) { global $global; if (empty($url)) { return false; } return isSameDomain($url, $global['webSiteRootURL']); } function requestComesFromSameDomainAsMyAVideo() { global $global; $url = ""; if (!empty($_SERVER['HTTP_REFERER'])) { $url = $_SERVER['HTTP_REFERER']; } elseif (!empty($_SERVER['HTTP_ORIGIN'])) { $url = $_SERVER['HTTP_ORIGIN']; } return isSameDomain($url, $global['webSiteRootURL']); } function requestComesFromSafePlace() { return (requestComesFromSameDomainAsMyAVideo() || isAVideo()); } function addGlobalTokenIfSameDomain($url) { if (!filter_var($url, FILTER_VALIDATE_URL) || (empty($_GET['livelink']) || !preg_match("/^http.*/i", $_GET['livelink']))) { return $url; } if (!isSameDomainAsMyAVideo($url)) { return $url; } return addQueryStringParameter($url, 'globalToken', getToken(60)); } /** * Remove a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function removeQueryStringParameter($url, $varname) { $parsedUrl = parse_url($url); $query = array(); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); unset($query[$varname]); } $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; return $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $path . $query; } /** * Add a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function addQueryStringParameter($url, $varname, $value) { $parsedUrl = parse_url($url); $query = array(); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); } $query[$varname] = $value; $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; return $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $path . $query; } function isSameDomain($url1, $url2) { if (empty($url1) || empty($url2)) { return false; } return (get_domain($url1) === get_domain($url2)); } function isAVideoStreamer($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoStreamer_UA; if (preg_match("/{$AVideoStreamer_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoStorage($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoStorage_UA; if (preg_match("/{$AVideoStorage_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function get_domain($url, $ifEmptyReturnSameString = false) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (empty($domain)) { return $ifEmptyReturnSameString ? $url : false; } if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } else { $isIp = (bool) ip2long($pieces['host']); if ($isIp) { return $pieces['host']; } } return false; } function siteMap() { _error_log("siteMap: start"); ini_set('memory_limit', '-1'); ini_set('max_execution_time', 0); global $global, $advancedCustom; $date = date('Y-m-d\TH:i:s') . "+00:00"; $xml = ' ' . $global['webSiteRootURL'] . ' ' . $date . ' always 1.00 ' . $global['webSiteRootURL'] . 'help ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'about ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'contact ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'channels ' . $date . ' daily 0.80 '; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit; _error_log("siteMap: rowCount {$_REQUEST['rowCount']} "); $_POST['sort']['modified'] = "DESC"; $users = User::getAllUsersThatHasVideos(true); _error_log("siteMap: getAllUsers " . count($users)); foreach ($users as $value) { $xml .= ' ' . User::getChannelLink($value['id']) . ' ' . $date . ' daily 0.90 '; } $xml .= ' '; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit; $_POST['sort']['modified'] = "DESC"; $rows = Category::getAllCategories(); _error_log("siteMap: getAllCategories " . count($rows)); foreach ($rows as $value) { $xml .= ' ' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . ' ' . $date . ' weekly 0.80 '; } $xml .= ''; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10; $_POST['sort']['created'] = "DESC"; $rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap) ? "viewableNotUnlisted" : "publicOnly"); _error_log("siteMap: getAllVideos " . count($rows)); foreach ($rows as $video) { $videos_id = $video['id']; //_error_log("siteMap: getAllVideos videos_id {$videos_id} start"); $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } elseif ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = parseDurationToSeconds($video['duration']); if ($duration > 28800) { // this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore $duration = 28800; } $xml .= ' ' . Video::getLink($video['id'], $video['clean_title']) . ' ' . $img . ' ' . $duration . ' ' . $video['views_count'] . ' ' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00 yes ' . (Video::isPublic($video['id']) ? "no" : "yes") . ' ' . User::getNameIdentificationById($video['users_id']) . ' no '; } $xml .= ' '; _error_log("siteMap: done "); $newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml); if (empty($newXML1)) { _error_log("siteMap: pregreplace1 fail "); $newXML1 = $xml; } if(!empty($advancedCustom->siteMapUTF8Fix)){ $newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1); if (empty($newXML2)) { _error_log("siteMap: pregreplace2 fail "); $newXML2 = $newXML1; } $newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2); if (empty($newXML3)) { _error_log("siteMap: pregreplace3 fail "); $newXML3 = $newXML2; } $newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3); if (empty($newXML4)) { _error_log("siteMap: pregreplace4 fail "); $newXML4 = $newXML3; } $newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4); if (empty($newXML5)) { _error_log("siteMap: pregreplace5 fail "); $newXML5 = $newXML4; } }else{ $newXML5 = $newXML1; } return $newXML5; } function object_to_array($obj) { //only process if it's an object or array being passed to the function if (is_object($obj) || is_array($obj)) { $ret = (array) $obj; foreach ($ret as &$item) { //recursively process EACH element regardless of type $item = object_to_array($item); } return $ret; } //otherwise (i.e. for scalar values) return without modification else { return $obj; } } function allowOrigin() { global $global; if (empty($_SERVER['HTTP_ORIGIN'])) { $server = parse_url($global['webSiteRootURL']); header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com'); } else { header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); } header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT"); header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); } function rrmdir($dir) { global $global; if ($dir == "{$global['systemRootPath']}videos/" || $dir == "{$global['systemRootPath']}videos") { return false; } if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . "/" . $object)) { rrmdir($dir . "/" . $object); } else { unlink($dir . "/" . $object); } } } rmdir($dir); } } /** * You can now configure it on the configuration.php * @return boolean */ function ddosProtection() { global $global; $maxCon = empty($global['ddosMaxConnections']) ? 40 : $global['ddosMaxConnections']; $secondTimeout = empty($global['ddosSecondTimeout']) ? 5 : $global['ddosSecondTimeout']; $whitelistedFiles = array( 'playlists.json.php', 'playlistsFromUserVideos.json.php', 'image404.php' ); if (in_array(basename($_SERVER["SCRIPT_FILENAME"]), $whitelistedFiles)) { return true; } $time = time(); if (!isset($_SESSION['bruteForceBlock']) || empty($_SESSION['bruteForceBlock'])) { $_SESSION['bruteForceBlock'] = array(); $_SESSION['bruteForceBlock'][] = $time; return true; } $_SESSION['bruteForceBlock'][] = $time; //remove requests that are older than secondTimeout foreach ($_SESSION['bruteForceBlock'] as $key => $request_time) { if ($request_time < $time - $secondTimeout) { unset($_SESSION['bruteForceBlock'][$key]); } } //progressive timeout-> more requests, longer timeout $active_connections = count($_SESSION['bruteForceBlock']); $timeoutReal = ($active_connections / $maxCon) < 1 ? 0 : ($active_connections / $maxCon) * $secondTimeout; if ($timeoutReal) { _error_log("ddosProtection:: progressive timeout timeoutReal = ($timeoutReal) active_connections = ($active_connections) maxCon = ($maxCon) ", AVideoLog::$SECURITY); } sleep($timeoutReal); //with strict mode, penalize "attacker" with sleep() above, log and then die if ($global['strictDDOSprotection'] && $timeoutReal > 0) { $str = "bruteForceBlock: maxCon: $maxCon => secondTimeout: $secondTimeout | IP: " . getRealIpAddr() . " | count:" . count($_SESSION['bruteForceBlock']); _error_log($str); die($str); } return true; } function getAdsLeaderBoardBigVideo() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardBigVideoMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardBigVideo->value); } } } function getAdsLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardTop->value); } } } function getAdsChannelLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->channelLeaderBoardTopMobile->value); } else { return ADs::giveGoogleATimeout($ad->channelLeaderBoardTop->value); } } } function getAdsLeaderBoardTop2() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile2->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardTop2->value); } } } function getAdsLeaderBoardMiddle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardMiddleMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardMiddle->value); } } } function getAdsLeaderBoardFooter() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardFooterMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardFooter->value); } } } function getAdsSideRectangle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->sideRectangle->value); } else { return ADs::giveGoogleATimeout($ad->sideRectangle->value); } } } function isToHidePrivateVideos() { $obj = AVideoPlugin::getObjectDataIfEnabled("Gallery"); if (!empty($obj)) { return $obj->hidePrivateVideos; } $obj = AVideoPlugin::getObjectDataIfEnabled("YouPHPFlix2"); if (!empty($obj)) { return $obj->hidePrivateVideos; } $obj = AVideoPlugin::getObjectDataIfEnabled("YouTube"); if (!empty($obj)) { return $obj->hidePrivateVideos; } return false; } function convertImageToOG($source, $destination) { if (!file_exists($destination)) { $w = 200; $h = 200; $sizes = getimagesize($source); if ($sizes[0] < $w || $sizes[1] < $h) { $tmpDir = getTmpDir(); $fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg"; convertImage($source, $fileConverted, 100); im_resizeV2($fileConverted, $destination, $w, $h, 100); unlink($fileConverted); } } return $destination; } function convertImageToRoku($source, $destination) { if (empty($source)) { _error_log("convertImageToRoku: source image is empty"); return false; } $w = 1280; $h = 720; if (file_exists($destination)) { $sizes = getimagesize($destination); if ($sizes[0] < $w || $sizes[1] < $h) { _error_log("convertImageToRoku: file is smaller " . json_encode($sizes)); unlink($destination); } } if (!file_exists($destination)) { try { $tmpDir = getTmpDir(); $fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg"; convertImage($source, $fileConverted, 100); im_resizeV2($fileConverted, $destination, $w, $h, 100); @unlink($fileConverted); } catch (Exception $exc) { _error_log("convertImageToRoku: " . $exc->getMessage()); return false; } } return $destination; } function ogSite() { global $global, $config; include $global['systemRootPath'] . 'objects/functionogSite.php'; } function getOpenGraph($videos_id) { global $global, $config, $advancedCustom; include $global['systemRootPath'] . 'objects/functiongetOpenGraph.php'; } function getLdJson($videos_id) { $cache = ObjectYPT::getCache("getLdJson{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } elseif ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCache("getLdJson{$videos_id}", $output); echo $output; } function getItemprop($videos_id) { $cache = ObjectYPT::getCache("getItemprop{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } elseif ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'image') { $type = 'image'; } if ($video['type'] === 'zip') { $type = 'zip'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCache("getItemprop{$videos_id}", $output); echo $output; } function getOS($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } $os_platform = "Unknown OS Platform"; $os_array = array( '/windows nt 10/i' => 'Windows 10', '/windows nt 6.3/i' => 'Windows 8.1', '/windows nt 6.2/i' => 'Windows 8', '/windows nt 6.1/i' => 'Windows 7', '/windows nt 6.0/i' => 'Windows Vista', '/windows nt 5.2/i' => 'Windows Server 2003/XP x64', '/windows nt 5.1/i' => 'Windows XP', '/windows xp/i' => 'Windows XP', '/windows nt 5.0/i' => 'Windows 2000', '/windows me/i' => 'Windows ME', '/win98/i' => 'Windows 98', '/win95/i' => 'Windows 95', '/win16/i' => 'Windows 3.11', '/macintosh|mac os x/i' => 'Mac OS X', '/mac_powerpc/i' => 'Mac OS 9', '/linux/i' => 'Linux', '/ubuntu/i' => 'Ubuntu', '/iphone/i' => 'iPhone', '/ipod/i' => 'iPod', '/ipad/i' => 'iPad', '/android/i' => 'Android', '/blackberry/i' => 'BlackBerry', '/webos/i' => 'Mobile' ); foreach ($os_array as $regex => $value) { if (preg_match($regex, $user_agent)) { $os_platform = $value; } } return $os_platform; } function get_browser_name($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return 'Unknow'; } // Make case insensitive. $t = strtolower($user_agent); // If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space. // "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE." // http://php.net/manual/en/function.strpos.php $t = " " . $t; // Humans / Regular Users if (isAVideoStreamer($t)) { return 'AVideo Mobile App'; } elseif ($url = isAVideoEncoder($t)) { return 'AVideo Encoder ' . $url; } elseif ($url = isAVideoStreamer($t)) { return 'AVideo Streamer ' . $url; } elseif (strpos($t, 'crkey')) { return 'Chromecast'; } elseif (strpos($t, 'opera') || strpos($t, 'opr/')) { return 'Opera'; } elseif (strpos($t, 'edge')) { return 'Edge'; } elseif (strpos($t, 'chrome')) { return 'Chrome'; } elseif (strpos($t, 'safari')) { return 'Safari'; } elseif (strpos($t, 'firefox')) { return 'Firefox'; } elseif (strpos($t, 'msie') || strpos($t, 'trident/7')) { return 'Internet Explorer'; } elseif (strpos($t, 'applecoremedia')) { return 'Native Apple Player'; } // Search Engines elseif (strpos($t, 'google')) { return '[Bot] Googlebot'; } elseif (strpos($t, 'bing')) { return '[Bot] Bingbot'; } elseif (strpos($t, 'slurp')) { return '[Bot] Yahoo! Slurp'; } elseif (strpos($t, 'duckduckgo')) { return '[Bot] DuckDuckBot'; } elseif (strpos($t, 'baidu')) { return '[Bot] Baidu'; } elseif (strpos($t, 'yandex')) { return '[Bot] Yandex'; } elseif (strpos($t, 'sogou')) { return '[Bot] Sogou'; } elseif (strpos($t, 'exabot')) { return '[Bot] Exabot'; } elseif (strpos($t, 'msn')) { return '[Bot] MSN'; } // Common Tools and Bots elseif (strpos($t, 'mj12bot')) { return '[Bot] Majestic'; } elseif (strpos($t, 'ahrefs')) { return '[Bot] Ahrefs'; } elseif (strpos($t, 'semrush')) { return '[Bot] SEMRush'; } elseif (strpos($t, 'rogerbot') || strpos($t, 'dotbot')) { return '[Bot] Moz or OpenSiteExplorer'; } elseif (strpos($t, 'frog') || strpos($t, 'screaming')) { return '[Bot] Screaming Frog'; } // Miscellaneous elseif (strpos($t, 'facebook')) { return '[Bot] Facebook'; } elseif (strpos($t, 'pinterest')) { return '[Bot] Pinterest'; } // Check for strings commonly used in bot user agents elseif (strpos($t, 'crawler') || strpos($t, 'api') || strpos($t, 'spider') || strpos($t, 'http') || strpos($t, 'bot') || strpos($t, 'archive') || strpos($t, 'info') || strpos($t, 'data')) { return '[Bot] Other'; } //_error_log("Unknow user agent ($t) IP=" . getRealIpAddr() . " URI=" . getRequestURI()); return 'Other (Unknown)'; } /** * Due some error on old chrome browsers (version < 70) on decrypt HLS keys with the videojs versions greater then 7.9.7 * we need to detect the chrome browser and load an older version * */ function isOldChromeVersion() { $global; if (empty($_SERVER['HTTP_USER_AGENT'])) { return false; } if (!empty($global['forceOldChrome'])) { return true; } if (preg_match('/Chrome\/([0-9.]+)/i', $_SERVER['HTTP_USER_AGENT'], $matches)) { return version_compare($matches[1], '80', '<='); } return false; } function TimeLogStart($name) { global $global; if (!empty($global['noDebug'])) { return false; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; if (empty($global['start']) || !is_array($global['start'])) { $global['start'] = array(); } $global['start'][$name] = $time; } function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) { global $global; if (!empty($global['noDebug'])) { return false; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $global['start'][$name]), 4); if ($total_time > $TimeLogLimit) { _error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}"); } TimeLogStart($name); } class AVideoLog { public static $DEBUG = 0; public static $WARNING = 1; public static $ERROR = 2; public static $SECURITY = 3; } function _error_log($message, $type = 0, $doNotRepeat = false) { if (empty($doNotRepeat)) { // do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error $doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']); } if ($doNotRepeat) { return false; } global $global; if (!empty($global['noDebug']) && $type == 0) { return false; } $prefix = "AVideoLog::"; switch ($type) { case AVideoLog::$DEBUG: $prefix .= "DEBUG: "; break; case AVideoLog::$WARNING: $prefix .= "WARNING: "; break; case AVideoLog::$ERROR: $prefix .= "ERROR: "; break; case AVideoLog::$SECURITY: $prefix .= "SECURITY: "; break; } error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}"); } function postVariables($url, $array) { if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { return false; } $array = object_to_array($array); $ch = curl_init($url); @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $array); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // execute! $response = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // close the connection, release resources used curl_close($ch); if ($httpcode == 200) { return true; } return $httpcode; } function _session_start(array $options = array()) { try { if (session_status() == PHP_SESSION_NONE) { return @session_start($options); } } catch (Exception $exc) { _error_log("_session_start: " . $exc->getTraceAsString()); return false; } } function _mysql_connect() { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if (is_object($global['mysqli']) && empty(@$global['mysqli']->ping())) { try { $global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort); if (!empty($global['mysqli_charset'])) { $global['mysqli']->set_charset($global['mysqli_charset']); } } catch (Exception $exc) { _error_log($exc->getTraceAsString()); return false; } } } function _mysql_close() { global $global; if (is_object($global['mysqli']) && !empty(@$global['mysqli']->ping())) { @$global['mysqli']->close(); } } function remove_utf8_bom($text) { if (strlen($text) > 1000000) { return $text; } $bom = pack('H*', 'EFBBBF'); $text = preg_replace("/^$bom/", '', $text); return $text; } function getCacheDir() { $p = AVideoPlugin::loadPlugin("Cache"); return $p->getCacheDir(); } function clearCache() { global $global; $dir = "{$global['systemRootPath']}videos/cache/"; if (!empty($_GET['FirstPage'])) { $dir .= "firstPage/"; } rrmdir($dir); $dir = getCacheDir(); if (!empty($_GET['FirstPage'])) { $dir .= "firstPage/"; } rrmdir($dir); ObjectYPT::deleteCache("getEncoderURL"); } function getUsageFromFilename($filename, $dir = "") { global $global; if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage return 0; } if (empty($dir)) { $dir = "{$global['systemRootPath']}videos/"; } $pos = strrpos($dir, '/'); $dir .= (($pos === false) ? "/" : ""); $totalSize = 0; _error_log("getUsageFromFilename: start {$dir}{$filename}"); //$files = glob("{$dir}{$filename}*"); $files = globVideosDir($filename); session_write_close(); $filesProcessed = array(); if (empty($files)) { _error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one"); file_put_contents("{$dir}{$filename}.notfound", time()); $totalSize = 10; } else { foreach ($files as $f) { if (strpos($f, '.size.lock') !== false) { continue; } if (is_dir($f)) { _error_log("getUsageFromFilename: {$f} is Dir"); $dirSize = getDirSize($f); $totalSize += $dirSize; if ($dirSize < 10000 && AVideoPlugin::isEnabledByName('YPTStorage')) { // probably the HLS file is hosted on the YPTStorage $info = YPTStorage::getFileInfo($filename); if (!empty($info->size)) { $totalSize += $info->size; } } } elseif (is_file($f)) { $filesize = filesize($f); if ($filesize < 20) { // that means it is a dummy file $lockFile = $f . ".size.lock"; if (!file_exists($lockFile) || (time() - 600) > filemtime($lockFile)) { file_put_contents($lockFile, time()); _error_log("getUsageFromFilename: {$f} is Dummy file ({$filesize})"); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); //$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); if (!empty($aws_s3)) { _error_log("getUsageFromFilename: Get from S3"); $filesize += $aws_s3->getFilesize($filename); } elseif (!empty($bb_b2)) { // TODO } else { $urls = Video::getVideosPaths($filename, true); _error_log("getUsageFromFilename: Paths " . json_encode($urls)); if (!empty($urls["m3u8"]['url'])) { $filesize += getUsageFromURL($urls["m3u8"]['url']); } if (!empty($urls['mp4'])) { foreach ($urls['mp4'] as $mp4) { if (in_array($mp4, $filesProcessed)) { continue; } $filesProcessed[] = $mp4; $filesize += getUsageFromURL($mp4); } } if (!empty($urls['webm'])) { foreach ($urls['webm'] as $mp4) { if (in_array($mp4, $filesProcessed)) { continue; } $filesProcessed[] = $mp4; $filesize += getUsageFromURL($mp4); } } if (!empty($urls["pdf"]['url'])) { $filesize += getUsageFromURL($urls["pdf"]['url']); } if (!empty($urls["image"]['url'])) { $filesize += getUsageFromURL($urls["image"]['url']); } if (!empty($urls["zip"]['url'])) { $filesize += getUsageFromURL($urls["zip"]['url']); } if (!empty($urls["mp3"]['url'])) { $filesize += getUsageFromURL($urls["mp3"]['url']); } } unlink($lockFile); } } else { _error_log("getUsageFromFilename: {$f} is File ({$filesize})"); } $totalSize += $filesize; } } } return $totalSize; } /** * Returns the size of a file without downloading it, or -1 if the file * size could not be determined. * * @param $url - The location of the remote file to download. Cannot * be null or empty. * * @return The size of the file referenced by $url, or false if the size * could not be determined. */ function getUsageFromURL($url) { global $global; if (!empty($global['doNotGetUsageFromURL'])) { // manually add this variable in your configuration.php file to not scan your video usage return 0; } _error_log("getUsageFromURL: start ({$url})"); // Assume failure. $result = false; $curl = curl_init($url); _error_log("getUsageFromURL: curl_init "); try { // Issue a HEAD request and follow any redirects. curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //curl_setopt($curl, CURLOPT_USERAGENT, get_user_agent_string()); $data = curl_exec($curl); } catch (Exception $exc) { echo $exc->getTraceAsString(); _error_log("getUsageFromURL: ERROR " . $exc->getMessage()); _error_log("getUsageFromURL: ERROR " . curl_errno($curl)); _error_log("getUsageFromURL: ERROR " . curl_error($curl)); } if ($data) { _error_log("getUsageFromURL: response header " . $data); $content_length = "unknown"; $status = "unknown"; if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) { $status = (int) $matches[1]; } if (preg_match("/Content-Length: (\d+)/", $data, $matches)) { $content_length = (int) $matches[1]; } // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes if ($status == 200 || ($status > 300 && $status <= 308)) { $result = $content_length; } } else { _error_log("getUsageFromURL: ERROR no response data " . curl_error($curl)); } curl_close($curl); return (int) $result; } function getDirSize($dir) { _error_log("getDirSize: start {$dir}"); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return foldersize($dir); } else { $command = "du -sb {$dir}"; exec($command . " < /dev/null 2>&1", $output, $return_val); if ($return_val !== 0) { _error_log("getDirSize: ERROR ON Command {$command}"); return 0; } else { if (!empty($output[0])) { preg_match("/^([0-9]+).*/", $output[0], $matches); } if (!empty($matches[1])) { _error_log("getDirSize: found {$matches[1]} from - {$output[0]}"); return intval($matches[1]); } _error_log("getDirSize: ERROR on pregmatch {$output[0]}"); return 0; } } } function foldersize($path) { $total_size = 0; $files = scandir($path); $cleanPath = rtrim($path, '/') . '/'; foreach ($files as $t) { if ($t <> "." && $t <> "..") { $currentFile = $cleanPath . $t; if (is_dir($currentFile)) { $size = foldersize($currentFile); $total_size += $size; } else { $size = filesize($currentFile); $total_size += $size; } } } return $total_size; } function getDiskUsage() { global $global; $dir = "{$global['systemRootPath']}videos/"; $obj = new stdClass(); $obj->disk_free_space = disk_free_space($dir); $obj->disk_total_space = disk_total_space($dir); $obj->videos_dir = getDirSize($dir); $obj->disk_used = $obj->disk_total_space - $obj->disk_free_space; $obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir; $obj->disk_free_space_human = humanFileSize($obj->disk_free_space); $obj->disk_total_space_human = humanFileSize($obj->disk_total_space); $obj->videos_dir_human = humanFileSize($obj->videos_dir); $obj->disk_used_human = humanFileSize($obj->disk_used); $obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other); // percentage of disk used $obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100); $obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100); $obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100); return $obj; } function unsetSearch() { unset($_GET['searchPhrase']); unset($_POST['searchPhrase']); unset($_GET['search']); unset($_GET['q']); } function encrypt_decrypt($string, $action) { global $global; $output = false; $encrypt_method = "AES-256-CBC"; $secret_key = 'This is my secret key'; $secret_iv = $global['systemRootPath']; while (strlen($secret_iv) < 16) { $secret_iv .= $global['systemRootPath']; } // hash $key = hash('sha256', $global['salt']); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } elseif ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } return $output; } function compressString($string) { if (function_exists("gzdeflate")) { $string = gzdeflate($string, 9); } return $string; } function decompressString($string) { if (function_exists("gzinflate")) { $string = gzinflate($string); } return $string; } function encryptString($string) { if (is_object($string)) { $string = json_encode($string); } return encrypt_decrypt($string, 'encrypt'); } function decryptString($string) { return encrypt_decrypt($string, 'decrypt'); } function getToken($timeout = 0, $salt = "") { global $global; $obj = new stdClass(); $obj->salt = $global['salt'] . $salt; if (!empty($timeout)) { $obj->time = time(); $obj->timeout = $obj->time + $timeout; } else { $obj->time = strtotime("Today 00:00:00"); $obj->timeout = strtotime("Today 23:59:59"); $obj->timeout += cacheExpirationTime(); } $strObj = json_encode($obj); //_error_log("Token created: {$strObj}"); return encryptString($strObj); } function verifyToken($token, $salt = "") { global $global; $obj = json_decode(decryptString($token)); if (empty($obj)) { _error_log("verifyToken invalid token"); return false; } if ($obj->salt !== $global['salt'] . $salt) { _error_log("verifyToken salt fail"); return false; } $time = time(); if (!($time >= $obj->time && $time <= $obj->timeout)) { _error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout"); return false; } return true; } class YPTvideoObject { public $id; public $title; public $description; public $thumbnails; public $channelTitle; public $videoLink; public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) { $this->id = $id; $this->title = $title; $this->description = $description; $this->thumbnails = $thumbnails; $this->channelTitle = $channelTitle; $this->videoLink = $videoLink; } } function isToShowDuration($type) { $notShowTo = array('pdf', 'article', 'serie', 'zip', 'image'); if (in_array($type, $notShowTo)) { return false; } else { return true; } } function _dieAndLogObject($obj, $prefix = "") { $objString = json_encode($obj); _error_log($prefix . $objString); die($objString); } function isAVideoPlayer() { if (isVideo()) { return true; } return false; } function isVideo() { global $isModeYouTube; return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive(); } function isAudio() { global $isAudio; return !empty($isAudio); } function isSerie() { return isPlayList(); } function isPlayList() { global $isPlayList, $isSerie; return !empty($isSerie) || !empty($isPlayList); } function isChannel() { global $isChannel; if (!empty($isChannel) && !isVideo()) { $user_id = 0; if (empty($_GET['channelName'])) { if (User::isLogged()) { $user_id = User::getId(); } else { return false; } } else { $_GET['channelName'] = xss_esc($_GET['channelName']); $user = User::getChannelOwner($_GET['channelName']); if (!empty($user)) { $user_id = $user['id']; } else { $user_id = $_GET['channelName']; } } return $user_id; } return false; } function isEmbed() { global $isEmbed; return !empty($isEmbed); } function isLive() { global $isLive; return !empty($isLive); } function isVideoPlayerHasProgressBar() { if (isLive()) { $obj = AVideoPlugin::getObjectData('Live'); if (empty($obj->disableDVR)) { return true; } } elseif (isAVideoPlayer()) { return true; } return false; } function isHLS() { global $video, $global; if (isLive()) { return true; } elseif (!empty($video) && $video['type'] == 'video' && file_exists("{$global['systemRootPath']}videos/{$video['filename']}/index.m3u8")) { return true; } return false; } function getRedirectUri() { if (!empty($_GET['redirectUri'])) { return $_GET['redirectUri']; } if (!empty($_SERVER["HTTP_REFERER"])) { return $_SERVER["HTTP_REFERER"]; } return getRequestURI(); } function getRequestURI() { if (empty($_SERVER['REQUEST_URI'])) { return ""; } return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; } function getSelfURI() { if (empty($_SERVER['PHP_SELF'])) { return ""; } $queryStringWithoutError = preg_replace("/error=[^&]*/", "", $_SERVER['QUERY_STRING']); $phpselfWithoutIndex = preg_replace("/index.php/", "", $_SERVER['PHP_SELF']); $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError"; $url = rtrim($url, '?'); return $url; } function isSameVideoAsSelfURI($url) { return URLsAreSameVideo($url, getSelfURI()); } function URLsAreSameVideo($url1, $url2) { return getVideoIDFromURL($url1) == getVideoIDFromURL($url2); } function getVideoIDFromURL($url) { if (preg_match("/v=([0-9]+)/", $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/video\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/videoEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/v\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/vEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/article\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/articleEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } } function getBackURL() { global $global; $backURL = getRedirectUri(); if (empty($backURL)) { $backURL = getRequestURI(); } if (isSameVideoAsSelfURI($backURL)) { $backURL = getHomeURL(); } return $backURL; } function getHomeURL() { global $global, $advancedCustomUser, $advancedCustom; if (isValidURL($advancedCustomUser->afterLoginGoToURL)) { return $advancedCustomUser->afterLoginGoToURL; } elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) { return $advancedCustom->logoMenuBarURL; } return $global['webSiteRootURL']; } function isValidURL($url) { if (empty($url) || !is_string($url)) { return false; } if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) { return true; } return false; } function hasLastSlash($word) { return substr($word, -1) === '/'; } function addLastSlash($word) { return $word . (hasLastSlash($word) ? "" : "/"); } function URLHasLastSlash() { return hasLastSlash($_SERVER["REQUEST_URI"]); } function ucname($str) { - $str = ucwords(strtolower($str)); + $str = ucwords(strtolower($str)); - foreach(array('\'', '-') as $delim) { - if (strpos($str, $delim) !== false) { - $str = implode($delim, array_map('ucfirst', explode($delim, $str))); - } - } - return $str; + foreach(array('\'', '-') as $delim) { + if (strpos($str, $delim) !== false) { + $str = implode($delim, array_map('ucfirst', explode($delim, $str))); + } + } + return $str; } function sanitize_input($input) { return htmlentities(strip_tags($input)); } function sanitize_array_item(&$item, $key) { $item = sanitize_input($item); } function getSEOComplement($parameters = array()) { global $config; $allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null; $addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true; $addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true; $parts = array(); if (!empty($_GET['error'])) { array_push($parts, __("Error")); } if ($addCategory && !empty($_GET['catName'])) { array_push($parts, $_GET['catName']); } if (!empty($_GET['channelName'])) { array_push($parts, $_GET['channelName']); } if (!empty($_GET['type'])) { $type = $_GET['type']; if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) { array_push($parts, __(ucname($type))); } } if (!empty($_GET['showOnly'])) { array_push($parts, $_GET['showOnly']); } if (!empty($_GET['page'])) { $page = intval($_GET['page']); if ($page > 1) { array_push($parts, sprintf(__("Page %d"), $page)); } } // Cleaning all entries in the $parts array array_walk($parts, 'sanitize_array_item'); $txt = implode($config->getPageTitleSeparator(), $parts); $txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt; return $txt; } function getCurrentPage() { if (!empty($_REQUEST['current'])) { return intval($_REQUEST['current']); } elseif (!empty($_POST['current'])) { return intval($_POST['current']); } elseif (!empty($_GET['current'])) { return intval($_GET['current']); } elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid $start = intval($_GET['start']); $length = intval($_GET['length']); if (!empty($start) && !empty($length)) { return floor($start / $length) + 1; } } return 1; } function getRowCount($default = 1000) { global $global; if (!empty($_REQUEST['rowCount'])) { $defaultN = intval($_REQUEST['rowCount']); } elseif (!empty($_POST['rowCount'])) { $defaultN = intval($_POST['rowCount']); } elseif (!empty($_GET['rowCount'])) { $defaultN = intval($_GET['rowCount']); } elseif (!empty($_REQUEST['length'])) { $defaultN = intval($_REQUEST['length']); } elseif (!empty($_POST['length'])) { $defaultN = intval($_POST['length']); } elseif (!empty($_GET['length'])) { $defaultN = intval($_GET['length']); } elseif (!empty($global['rowCount'])) { $defaultN = intval($global['rowCount']); } return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default; } function getSearchVar() { if (!empty($_REQUEST['search'])) { return $_REQUEST['search']; } elseif (!empty($_REQUEST['q'])) { return $_REQUEST['q']; } if (!empty($_REQUEST['searchPhrase'])) { return $_REQUEST['searchPhrase']; } elseif (!empty($_REQUEST['search']['value'])) { return $_REQUEST['search']['value']; } return ""; } $cleanSearchHistory = ""; function cleanSearchVar() { global $cleanSearchHistory; $search = getSearchVar(); if (!empty($search)) { $cleanSearchHistory = $search; } $searchIdex = array('q', 'searchPhrase', 'search'); foreach ($searchIdex as $value) { unset($_REQUEST[$value]); unset($_POST[$value]); unset($_GET[$value]); } } function reloadSearchVar() { global $cleanSearchHistory; $_REQUEST['search'] = $cleanSearchHistory; if (empty($_GET['search'])) { $_GET['search'] = $cleanSearchHistory; } if (empty($_POST['search'])) { $_POST['search'] = $cleanSearchHistory; } } function wget($url, $filename, $debug = false) { if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) { return false; } if (wgetIsLocked($url)) { if ($debug) { _error_log("wget: ERROR the url is already downloading $url, $filename"); } return false; } wgetLock($url); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $content = file_get_contents($url); if (!empty($content) && file_put_contents($filename, $content) > 100) { wgetRemoveLock($url); return true; } wgetRemoveLock($url); return false; } $cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate"; if ($debug) { _error_log("wget Start ({$cmd}) "); } //echo $cmd; exec($cmd); wgetRemoveLock($url); if (!file_exists($filename)) { _error_log("wget: ERROR the url does not download $url, $filename"); return false; } if (empty(filesize($filename))) { _error_log("wget: ERROR the url download but is empty $url, $filename"); return true; } return false; } function wgetLockFile($url) { return getTmpDir("YPTWget") . md5($url) . ".lock"; } function wgetLock($url) { $file = wgetLockFile($url); return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX); } function wgetRemoveLock($url) { $filename = wgetLockFile($url); if (!file_exists($filename)) { return false; } return unlink($filename); } function getLockFile($name) { return getTmpDir("YPTLockFile") . md5($name) . ".lock"; } function setLock($name) { $file = getLockFile($name); return file_put_contents($file, time()); } function isLock($name, $timeout = 60) { $file = getLockFile($name); if (file_exists($file)) { $time = intval(file_get_contents($file)); if ($time + $timeout < time()) { return false; } } } function removeLock($name) { $filename = getLockFile($name); if (!file_exists($filename)) { return false; } return unlink($filename); } function wgetIsLocked($url) { $filename = wgetLockFile($url); if (!file_exists($filename)) { return false; } $time = intval(file_get_contents($filename)); if (time() - $time > 36000) { // more then 10 hours unlink($filename); return false; } return true; } // due the some OS gives a fake is_writable response function isWritable($dir) { $dir = rtrim($dir, '/') . '/'; $file = $dir . uniqid(); $result = false; $time = time(); if (@file_put_contents($file, $time)) { if ($fileTime = @file_get_contents($file)) { if ($fileTime == $time) { $result = true; } } } @unlink($file); return $result; } function _isWritable($dir) { if (!isWritable($dir)) { return false; } $tmpFile = "{$dir}" . uniqid(); $bytes = @file_put_contents($tmpFile, time()); @unlink($tmpFile); return !empty($bytes); } function getTmpDir($subdir = "") { global $global; if (empty($_SESSION['getTmpDir'])) { $_SESSION['getTmpDir'] = array(); } if (empty($_SESSION['getTmpDir'][$subdir . "_"])) { $tmpDir = sys_get_temp_dir(); if (empty($tmpDir) || !_isWritable($tmpDir)) { $tmpDir = "{$global['systemRootPath']}videos/cache/"; } $tmpDir = rtrim($tmpDir, '/') . '/'; $tmpDir = "{$tmpDir}{$subdir}"; $tmpDir = rtrim($tmpDir, '/') . '/'; if (!is_dir($tmpDir)) { mkdir($tmpDir, 0755, true); } _session_start(); $_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir; } else { $tmpDir = $_SESSION['getTmpDir'][$subdir . "_"]; } return $tmpDir; } function getTmpFile() { return getTmpDir("tmpFiles") . uniqid(); } function getMySQLDate() { global $global; $sql = "SELECT now() as time FROM configurations LIMIT 1"; // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data['time']; } else { $row = false; } return $row; } function _file_put_contents($filename, $data, $flags = 0, $context = null) { make_path($filename); return file_put_contents($filename, $data, $flags, $context); } function html2plainText($html) { $text = strip_tags($html); $text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text)); return $text; } function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') { if (empty($paceholder)) { $paceholder = __("Password"); } ?>
>
>
" . PHP_EOL; } else { return __LINE__; } $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { echo "Error 1 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = utf8_encode($item); } }); $json = json_encode($objectEncoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = utf8_decode($item); } }); $json = json_encode($objectDecoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } return false; } function _json_encode($object) { if (empty($object)) { return false; } $json = json_encode($object); if (json_last_error()) { _error_log("_json_encode: Error 1 Found: " . json_last_error_msg()); $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { _error_log("_json_encode: Error 2 Found: " . json_last_error_msg()); $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 3 Found: " . json_last_error_msg()); $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = utf8_encode($item); } }); $json = json_encode($objectEncoded); if (json_last_error()) { _error_log("_json_encode: Error 4 Found: " . json_last_error_msg()); $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 5 Found: " . json_last_error_msg()); $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = utf8_decode($item); } }); $json = json_encode($objectDecoded); if (json_last_error()) { _error_log("_json_encode: Error 6 Found: " . json_last_error_msg()); $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 7 Found: " . json_last_error_msg()); } } } } } } } return $json; } // this will make sure the strring will fits in the database field function _substr($string, $start, $length = null) { // make sure the name is not chunked in case of multibyte string if (function_exists("mb_strcut")) { return mb_strcut($string, $start, $length, "UTF-8"); } else { return substr($string, $start, $length); } } function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") { global $global, $advancedCustom; if ($total < 2) { return ""; } $uid = md5($link); if ($total < $maxVisible) { $maxVisible = $total; } if (empty($link)) { $link = getSelfURI(); if (preg_match("/(current=[0-9]+)/i", $link, $match)) { $link = str_replace($match[1], "current={page}", $link); } else { $link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}'; } } if (empty($page)) { $page = getCurrentPage(); } $class = ""; if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) { $class = "infiniteScrollPagination{$uid} hidden"; } $pag = ' '; if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) { $content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php'); $pag .= str_replace( array('$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'), array($uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector), $content ); } return $pag; } function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv") { global $global, $advancedCustom; include $global['systemRootPath'] . 'objects/functiongetShareMenu.php'; } function getSharePopupButton($videos_id, $url = "", $title = "") { global $global, $advancedCustom; if ($advancedCustom->disableShareOnly || $advancedCustom->disableShareAndPlaylist) { return false; } $video['id'] = $videos_id; include $global['systemRootPath'] . 'view/include/socialModal.php'; } function forbiddenPage($message, $logMessage = false) { global $global; $_REQUEST['403ErrorMsg'] = $message; if ($logMessage) { _error_log($message); } include $global['systemRootPath'] . 'view/forbiddenPage.php'; exit; } function isForbidden() { global $global; if (!empty($global['isForbidden'])) { return true; } return false; } function diskUsageBars() { global $global; ob_start(); include $global['systemRootPath'] . 'objects/functiondiskUsageBars.php'; $contents = ob_get_contents(); ob_end_clean(); return $contents; } function getDomain() { global $global; if (empty($_SERVER['HTTP_HOST'])) { $parse = parse_url($global['webSiteRootURL']); return $parse['host']; } $domain = $_SERVER['HTTP_HOST']; $domain = str_replace("www.", "", $domain); $domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain; return $domain; } /** * It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc. * * From the IETF RFC4122: * 8-4-4-4-12 * @return string */ function getDeviceID() { if (empty($_SERVER['HTTP_USER_AGENT'])) { return "unknowDevice"; } $cookieName = "yptDeviceID"; if (empty($_COOKIE[$cookieName])) { if (empty($_GET[$cookieName])) { $_GET[$cookieName] = uniqidV4(); } if (empty($_SESSION[$cookieName])) { _session_start(); $_SESSION[$cookieName] = $_GET[$cookieName]; } else { $_GET[$cookieName] = $_SESSION[$cookieName]; } if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) { return "getDeviceIDError"; } $_COOKIE[$cookieName] = $_GET[$cookieName]; return $_GET[$cookieName]; } return $_COOKIE[$cookieName]; } function uniqidV4() { $randomString = openssl_random_pseudo_bytes(16); $time_low = bin2hex(substr($randomString, 0, 4)); $time_mid = bin2hex(substr($randomString, 4, 2)); $time_hi_and_version = bin2hex(substr($randomString, 6, 2)); $clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2)); $node = bin2hex(substr($randomString, 10, 6)); /** * Set the four most significant bits (bits 12 through 15) of the * time_hi_and_version field to the 4-bit version number from * Section 4.1.3. * @see http://tools.ietf.org/html/rfc4122#section-4.1.3 */ $time_hi_and_version = hexdec($time_hi_and_version); $time_hi_and_version = $time_hi_and_version >> 4; $time_hi_and_version = $time_hi_and_version | 0x4000; /** * Set the two most significant bits (bits 6 and 7) of the * clock_seq_hi_and_reserved to zero and one, respectively. */ $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved); $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2; $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000; return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node); } // guid function _setcookie($cookieName, $value, $expires = 0) { if (empty($expires)) { if (empty($config) || !is_object($config)) { $config = new Configuration(); } $expires = time() + $config->getSession_timeout(); } if (version_compare(phpversion(), '7.3', '>=')) { $cookie_options = array( 'expires' => $expires, 'path' => '/', 'domain' => getDomain(), 'secure' => true, 'httponly' => false, 'samesite' => 'None'); return setcookie($cookieName, $value, $cookie_options); } else { return setcookie($cookieName, $value, (int) $expires, "/", getDomain()); } } function _unsetcookie($cookieName) { $domain = getDomain(); $expires = strtotime("-10 years"); $value = ""; _setcookie($cookieName, $value, $expires); setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires); setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain)); setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain); setcookie($cookieName, $value, (int) $expires, "/", "." . $domain); setcookie($cookieName, $value, (int) $expires, "/", $domain); setcookie($cookieName, $value, (int) $expires, "/"); setcookie($cookieName, $value, (int) $expires); unset($_COOKIE[$cookieName]); } /** * This function is not 100% but try to tell if the site is in an iFrame * @global type $global * @return boolean */ function isIframeInDifferentDomain() { global $global; if (!isIframe()) { return false; } return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']); } function isIframe() { global $global; if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') { return true; } if (empty($_SERVER['HTTP_REFERER'])) { return false; } return true; } function getCredentialsURL() { global $global; return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1"; } function gotToLoginAndComeBackHere($msg) { global $global; if (!empty($_GET['comebackhere'])) { return false; } header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1"); exit; } function setAlertMessage($msg, $type = "msg") { _session_start(); $_SESSION['YPTalertMessage'][] = array($msg, $type); } function setToastMessage($msg) { setAlertMessage($msg, "toast"); } function showAlertMessage() { if (!empty($_SESSION['YPTalertMessage'])) { foreach ($_SESSION['YPTalertMessage'] as $value) { if (!empty($value[0])) { if (empty($_GET[$value[1]])) { $_GET[$value[1]] = array(); } $_GET[$value[1]][] = $value[0]; } } _session_start(); unset($_SESSION['YPTalertMessage']); } $joinString = array('error', 'msg', 'success'); foreach ($joinString as $value) { if (!empty($_GET[$value]) && is_array($_GET[$value])) { $_GET[$value] = array_unique($_GET[$value]); $newStr = array(); foreach ($_GET[$value] as $value2) { if (!empty($value2)) { $newStr[] = $value2; } } $_GET[$value] = implode("
", $newStr); } } $check = array('error', 'msg', 'success', 'toast'); foreach ($check as $value) { if (!empty($_GET[$value])) { if (is_array($_GET[$value])) { $newStr = array(); foreach ($_GET[$value] as $key => $value2) { $value2 = str_replace('"', "''", $value2); if (!empty($value2)) { $newStr[] = $value2; } } $_GET[$value] = $newStr; } else { $_GET[$value] = str_replace('"', "''", $_GET[$value]); } } } echo "/** showAlertMessage **/", PHP_EOL; if (!empty($_GET['error'])) { echo 'avideoAlertError("' . $_GET['error'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['msg'])) { echo 'avideoAlertInfo("' . $_GET['msg'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['success'])) { echo 'avideoAlertSuccess("' . $_GET['success'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['toast'])) { if (!is_array($_GET['toast'])) { $_GET['toast'] = array($_GET['toast']); } else { $_GET['toast'] = array_unique($_GET['toast']); } foreach ($_GET['toast'] as $key => $value) { $hideAfter = strlen(strip_tags($value)) * 150; if ($hideAfter < 3000) { $hideAfter = 3000; } if ($hideAfter > 15000) { $hideAfter = 15000; } echo '$.toast({ text: "' . $value . '", hideAfter: ' . $hideAfter . ' // in milli seconds });console.log("Toast Hide after ' . $hideAfter . '");'; } echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } echo PHP_EOL, "/** showAlertMessage END **/"; } function getResolutionLabel($res) { if ($res == 720) { return "" . getResolutionText($res) . ""; } elseif ($res == 1080) { return "" . getResolutionText($res) . ""; } elseif ($res == 1440) { return "" . getResolutionText($res) . ""; } elseif ($res == 2160) { return "" . getResolutionText($res) . ""; } elseif ($res == 4320) { return "" . getResolutionText($res) . ""; } else { return ''; } } function getResolutionText($res) { if ($res == 720) { return "HD"; } elseif ($res == 1080) { return "FHD"; } elseif ($res == 1440) { return "FHD+"; } elseif ($res == 2160) { return "4K"; } elseif ($res == 4320) { return "8K"; } else { return ''; } } // just realize the readdir is a lot faster then glob function _glob($dir, $pattern) { global $_glob; if (empty($dir)) { return array(); } if (empty($_glob)) { $_glob = array(); } $name = md5($dir . $pattern); if (isset($_glob[$name])) { return $_glob[$name]; } $dir = rtrim($dir, '/') . '/'; $array = array(); if ($handle = opendir($dir)) { $count = 0; while (false !== ($file_name = readdir($handle))) { if (preg_match($pattern, $file_name)) { $array[] = "{$dir}{$file_name}"; } } closedir($handle); } $_glob[$name] = $array; return $array; } function globVideosDir($filename, $filesOnly = false) { global $global; if (empty($filename)) { return array(); } $cleanfilename = Video::getCleanFilenameFromFile($filename); $pattern = "/{$cleanfilename}.*"; if (!empty($filesOnly)) { $formats = getValidFormats(); $pattern .= ".(" . implode("|", $formats) . ")"; } $pattern .= "/"; return _glob("{$global['systemRootPath']}videos/", $pattern); } function getValidFormats() { $video = array('webm', 'mp4', 'm3u8'); $audio = array('mp3', 'ogg'); $image = array('jpg', 'gif', 'webp'); return array_merge($video, $audio, $image); } function isValidFormats($format) { $format = str_replace(".", "", $format); return in_array($format, getValidFormats()); } function getTimerFromDates($startTime, $endTime = 0) { if (!is_int($startTime)) { $startTime = strtotime($startTime); } if (!is_int($endTime)) { $endTime = strtotime($endTime); } if (empty($endTime)) { $endTime = time(); } $timer = abs($endTime - $startTime); $uid = uniqid(); return ""; } function getServerClock() { $id = uniqid(); $today = getdate(); $html = '00:00:00'; $html .= ""; return $html; } /** * Xsendfile and FFMPEG are required for this feature * @global type $global * @param type $filepath * @return boolean */ function downloadHLS($filepath) { global $global; if (!CustomizeUser::canDownloadVideos()) { _error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO"); return false; } if (!file_exists($filepath)) { _error_log("downloadHLS: file NOT found: {$filepath}"); return false; } $videosDir = "{$global['systemRootPath']}videos/"; $outputfilename = str_replace($videosDir, "", $filepath); $parts = explode("/", $outputfilename); $resolution = Video::getResolutionFromFilename($filepath); $outputfilename = $parts[0] . "_{$resolution}_.mp4"; $outputpath = "{$videosDir}cache/downloads/{$outputfilename}"; make_path($outputpath); if (empty($outputfilename)) { _error_log("downloadHLS: empty outputfilename {$outputfilename}"); return false; } if (!empty($_REQUEST['title'])) { $quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['title']), '"\\')); } elseif (!empty($_REQUEST['file'])) { $quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['file']), '"\\')) . ".mp4"; } else { $quoted = $outputfilename; } $filepath = escapeshellcmd($filepath); $outputpath = escapeshellcmd($outputpath); if (true || !file_exists($outputpath)) { $command = get_ffmpeg() . " -allowed_extensions ALL -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}"; //var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit; exec($command . " 2>&1", $output, $return); if (!empty($return)) { _error_log("downloadHLS: " . implode(PHP_EOL, $output)); return false; } } //var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit; //var_dump($command, $outputpath);exit; header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename=' . $quoted); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header("X-Sendfile: {$outputpath}"); exit; } function getSocialModal($videos_id, $url = "", $title = "") { global $global; $video['id'] = $videos_id; $sharingUid = uniqid(); ob_start(); ?> $contents, 'id' => $sharingUid); } function getCroppie( $buttonTitle, $callBackJSFunction, $resultWidth, $resultHeight, $viewportWidth = 0, $boundary = 25, $viewportHeight = 0 ) { global $global; if (empty($viewportWidth)) { $viewportWidth = $resultWidth; } $zoom = 0; if (empty($viewportHeight)) { $zoom = ($viewportWidth / $resultWidth); $viewportHeight = $zoom * $resultHeight; } $boundaryWidth = $viewportWidth + $boundary; $boundaryHeight = $viewportHeight + $boundary; $uid = uniqid(); ob_start(); include $global['systemRootPath'] . 'objects/functionCroppie.php'; $contents = ob_get_contents(); ob_end_clean(); $callBackJSFunction = addcslashes($callBackJSFunction, "'"); return array( "html" => $contents, "id" => "croppie{$uid}", "uploadCropObject" => "uploadCrop{$uid}", "getCroppieFunction" => "getCroppie(uploadCrop{$uid}, '{$callBackJSFunction}', {$resultWidth}, {$resultHeight});", "createCroppie" => "createCroppie{$uid}", "restartCroppie" => "restartCroppie{$uid}" ); } function saveCroppieImage($destination, $postIndex = "imgBase64") { if (empty($_POST[$postIndex])) { return false; } $fileData = base64DataToImage($_POST[$postIndex]); return file_put_contents($destination, $fileData); } function get_ffmpeg($ignoreGPU = false) { global $global; //return 'ffmpeg -user_agent "'.getSelfUserAgent("FFMPEG").'" '; //return 'ffmpeg -headers "User-Agent: '.getSelfUserAgent("FFMPEG").'" '; $ffmpeg = 'ffmpeg '; if (empty($ignoreGPU) && !empty($global['ffmpegGPU'])) { $ffmpeg .= ' --enable-nvenc '; } if (!empty($global['ffmpeg'])) { $ffmpeg = "{$global['ffmpeg']}{$ffmpeg}"; } return $ffmpeg; } function isHTMLPage($url) { if ($type = getHeaderContentTypeFromURL($url)) { if (preg_match('/text\/html/i', $type)) { return true; } } return false; } function getHeaderContentTypeFromURL($url) { if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) { return $type; } return false; } function canFullScreen(){ global $doNotFullScreen; if(!empty($doNotFullScreen) || isSerie() || !isVideo()){ return false; } return true; -} \ No newline at end of file +} diff --git a/objects/getAllEmails.csv.php b/objects/getAllEmails.csv.php index 5cf599370..53eec12dd 100644 --- a/objects/getAllEmails.csv.php +++ b/objects/getAllEmails.csv.php @@ -1,26 +1,26 @@ query($sql)) { while ($p = $result->fetch_assoc()) { $users[] = $p; } } $output = fopen("php://output", 'w') or die("Can't open php://output"); header("Content-Type:application/csv"); header("Content-Disposition:attachment;filename=email.csv"); fputcsv($output, array('id', 'user', 'name', 'email', 'status', 'created', 'isAdmin')); -foreach ($users as $user) { +foreach ($users as $user) { fputcsv($output, $user); } fclose($output) or die("Can't close php://output"); diff --git a/objects/getTags.php b/objects/getTags.php index d231d1705..6da6ee5f8 100644 --- a/objects/getTags.php +++ b/objects/getTags.php @@ -1,19 +1,19 @@ doNotShowImportMP4Button)) { return false; } -if(!preg_match("/.*\\.mp4$/i", $_POST['fileURI'])){ +if (!preg_match("/.*\\.mp4$/i", $_POST['fileURI'])) { return false; } $obj = new stdClass(); $obj->error = true; $obj->fileURI = pathinfo($_POST['fileURI']); //get description -$filename = $obj->fileURI['dirname'].DIRECTORY_SEPARATOR.$obj->fileURI['filename']; +$filename = $obj->fileURI['dirname'] . DIRECTORY_SEPARATOR . $obj->fileURI['filename']; $extensions = array('txt', 'html', 'htm'); $length = intval($_POST['length']); -if(empty($length) || $length>100){ +if (empty($length) || $length>100) { $length = 100; } foreach ($extensions as $value) { $_POST['description'] = ""; $_POST['title'] = ""; - if(file_exists("{$filename}.{$value}")){ + if (file_exists("{$filename}.{$value}")) { $html = file_get_contents("{$filename}.{$value}"); - $breaks = array("
","
","
"); + $breaks = array("
","
","
"); $html = str_ireplace($breaks, "\r\n", $html); $_POST['description'] = $html; $cleanHTML = strip_tags($html); $_POST['title'] = substr($cleanHTML, 0, $length); break; } } $tmpDir = sys_get_temp_dir(); $tmpFileName = $tmpDir.DIRECTORY_SEPARATOR.$obj->fileURI['filename']; -$source = $obj->fileURI['dirname'].DIRECTORY_SEPARATOR.$obj->fileURI['basename']; +$source = $obj->fileURI['dirname'] . DIRECTORY_SEPARATOR . $obj->fileURI['basename']; if (!copy($source, $tmpFileName)) { $obj->msg = "failed to copy $filename...\n"; die(json_encode($obj)); } -if(!empty($_POST['delete']) && $_POST['delete']!=='false'){ - if(is_writable($source)){ +if (!empty($_POST['delete']) && $_POST['delete'] !== 'false') { + if (is_writable($source)) { unlink($source); foreach ($extensions as $value) { - if(file_exists("{$filename}.{$value}")){ + if (file_exists("{$filename}.{$value}")) { unlink("{$filename}.{$value}"); } } - }else{ + } else { $obj->msg = "Could not delete $source...\n"; } } $_FILES['upl']['error'] = 0; $_FILES['upl']['name'] = $obj->fileURI['basename']; $_FILES['upl']['tmp_name'] = $tmpFileName; -$_FILES['upl']['type'] = "video/mp4"; +$_FILES['upl']['type'] = 'video/mp4'; $_FILES['upl']['size'] = filesize($tmpFileName); require_once $global['systemRootPath'] . 'view/mini-upload-form/upload.php'; - -echo json_encode($obj); \ No newline at end of file +echo json_encode($obj); diff --git a/objects/include_config.php b/objects/include_config.php index 8d6cd09a2..3ef4bf01c 100644 --- a/objects/include_config.php +++ b/objects/include_config.php @@ -1,152 +1,154 @@ connect_errno)) { include $global['systemRootPath'] . 'view/include/offlinePage.php'; exit; } // if you set it on configuration file it will help you to encode if (!empty($global['mysqli_charset'])) { $global['mysqli']->set_charset($global['mysqli_charset']); } require_once $global['systemRootPath'] . 'objects/mysql_dal.php'; require_once $global['systemRootPath'] . 'objects/configuration.php'; require_once $global['systemRootPath'] . 'objects/security.php'; $config = new Configuration(); // for update config from old versions 2020-05-11 if (empty($global['webSiteRootPath']) || $global['configurationVersion'] < 3.1) { Configuration::rewriteConfigFile(); } $global['dont_show_us_flag'] = false; // this is for old versions session_write_close(); // server should keep session data for AT LEAST 1 hour ini_set('session.gc_maxlifetime', $config->getSession_timeout()); // each client should remember their session id for EXACTLY 1 hour session_set_cookie_params($config->getSession_timeout()); //Fix “set SameSite cookie to none” warning if (version_compare(PHP_VERSION, '7.3.0') >= 0) { setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]); } else { header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure'); setcookie('key', 'value', time() + $config->getSession_timeout(), "/; SameSite=None; Secure"); } session_start(); // DDOS protection can be disabled in video/configuration.php -if (!empty($global['enableDDOSprotection'])) +if (!empty($global['enableDDOSprotection'])) { ddosProtection(); +} // set the reffer for aVideo $url1['host'] = ""; $global["HTTP_REFERER"] = ""; if (!empty($_SERVER["HTTP_REFERER"])) { if (( - strpos($_SERVER["HTTP_REFERER"], '/video/') !== false || strpos($_SERVER["HTTP_REFERER"], '/v/') !== false) && + strpos($_SERVER["HTTP_REFERER"], '/video/') !== false || strpos($_SERVER["HTTP_REFERER"], '/v/') !== false + ) && !empty($_SESSION["LAST_HTTP_REFERER"])) { if (strpos($_SESSION["LAST_HTTP_REFERER"], 'cache/css/') !== false || strpos($_SESSION["LAST_HTTP_REFERER"], 'cache/js/') !== false || strpos($_SESSION["LAST_HTTP_REFERER"], 'cache/img/') !== false) { $_SESSION["LAST_HTTP_REFERER"] = $global['webSiteRootURL']; } $global["HTTP_REFERER"] = $_SESSION["LAST_HTTP_REFERER"]; $url1 = parse_url($global["HTTP_REFERER"]); } else { $global["HTTP_REFERER"] = $_SERVER["HTTP_REFERER"]; $url1 = parse_url($global["HTTP_REFERER"]); } } //var_dump($global["HTTP_REFERER"]);exit; if (!isset($_POST['redirectUri'])) { $_POST['redirectUri'] = ""; } if (!empty($_POST['redirectUri']) && strpos($_POST['redirectUri'], 'logoff.php') !== false) { $_POST['redirectUri'] = ''; } if (!empty($_GET['redirectUri']) && strpos($_GET['redirectUri'], 'logoff.php') !== false) { $_GET['redirectUri'] = ''; } $url2 = parse_url($global['webSiteRootURL']); if (!empty($url1['host']) && !empty($url2['host']) && $url1['host'] !== $url2['host']) { $global["HTTP_REFERER"] = $global['webSiteRootURL']; } $_SESSION["LAST_HTTP_REFERER"] = $global["HTTP_REFERER"]; //var_dump($global["HTTP_REFERER"], $url1);exit; $output = ob_get_clean(); ob_start("ob_gzhandler"); echo $output; $_SESSION['lastUpdate'] = time(); $_SESSION['savedQuerys'] = 0; require_once $global['systemRootPath'] . 'objects/Object.php'; require_once $global['systemRootPath'] . 'locale/function.php'; require_once $global['systemRootPath'] . 'objects/plugin.php'; require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; ObjectYPT::checkSessionCacheBasedOnLastDeleteALLCacheTime(); getDeviceID(); allowOrigin(); $baseName = basename($_SERVER["SCRIPT_FILENAME"]); if ($baseName !== 'xsendfile.php' && class_exists("Plugin")) { AVideoPlugin::getStart(); -} else if ($baseName !== 'xsendfile.php') { +} elseif ($baseName !== 'xsendfile.php') { _error_log("Class Plugin Not found: {$_SERVER['REQUEST_URI']}"); } if (empty($global['bodyClass'])) { $global['bodyClass'] = ""; } $global['allowedExtension'] = array('gif', 'jpg', 'mp4', 'webm', 'mp3', 'm4a', 'ogg', 'zip', 'm3u8'); $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); if (empty($global['disableTimeFix'])) { /* $now = new DateTime(); $mins = $now->getOffset() / 60; $sgn = ($mins < 0 ? -1 : 1); $mins = abs($mins); $hrs = floor($mins / 60); $mins -= $hrs * 60; $offset = sprintf('%+d:%02d', $hrs * $sgn, $mins); $global['mysqli']->query("SET time_zone='$offset';"); - * + * */ ObjectYPT::setTimeZone(); } $avideoLayout = AVideoPlugin::getObjectData("Layout"); $avideoCustomizeUser = $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); $avideoCustomize = $customizePlugin = AVideoPlugin::getObjectData("Customize"); $avideoPermissions = $permissionsPlugin = AVideoPlugin::getObjectData("Permissions"); $avideoPlayerSkins = AVideoPlugin::getObjectData("PlayerSkins"); $sitemapFile = "{$global['systemRootPath']}sitemap.xml"; if (!empty($_GET['type'])) { $metaDescription = " {$_GET['type']}"; -} else if (!empty($_GET['showOnly'])) { +} elseif (!empty($_GET['showOnly'])) { $metaDescription = " {$_GET['showOnly']}"; -} \ No newline at end of file +} diff --git a/objects/like.php b/objects/like.php index 3cd558f93..485964dcf 100644 --- a/objects/like.php +++ b/objects/like.php @@ -1,154 +1,164 @@ videos_id = $videos_id; $this->users_id = User::getId(); $this->load(); // if click again in the same vote, remove the vote if ($this->like == $like) { $like = 0; } $this->setLike($like); $this->save(); } - private function setLike($like) { + private function setLike($like) + { $like = intval($like); - if(!in_array($like, array(0,1,-1))){ + if (!in_array($like, array(0,1,-1))) { $like = 0; } $this->like = $like; } - private function load() { + private function load() + { $like = $this->getLike(); if (empty($like)) { return false; } foreach ($like as $key => $value) { $this->$key = $value; } } - private function getLike() { + private function getLike() + { global $global; if (empty($this->users_id) || empty($this->videos_id)) { header('Content-Type: application/json'); die('{"error":"You must have user and videos set to get a like"}'); } $sql = "SELECT * FROM likes WHERE users_id = ? AND videos_id = ".$this->videos_id." LIMIT 1;"; - $res = sqlDAL::readSql($sql,"i",array($this->users_id)); + $res = sqlDAL::readSql($sql, "i", array($this->users_id)); $dbLike = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $dbLike; } - private function save() { + private function save() + { global $global; - if(!User::isLogged()){ + if (!User::isLogged()) { header('Content-Type: application/json'); die('{"error":"'.__("Permission denied").'"}'); } if (!empty($this->id)) { $sql = "UPDATE likes SET `like` = ?, modified = now() WHERE id = ?;"; - $res = sqlDAL::writeSql($sql,"ii",array($this->like, $this->id)); + $res = sqlDAL::writeSql($sql, "ii", array($this->like, $this->id)); } else { $sql = "INSERT INTO likes (`like`,users_id, videos_id, created, modified) VALUES (?, ?, ?, now(), now());"; - $res = sqlDAL::writeSql($sql,"iii",array($this->like, $this->users_id, $this->videos_id)); + $res = sqlDAL::writeSql($sql, "iii", array($this->like, $this->users_id, $this->videos_id)); } //echo $sql; if ($global['mysqli']->errno!=0) { die('Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $res; } - static function getLikes($videos_id) { + public static function getLikes($videos_id) + { global $global; $obj = new stdClass(); $obj->videos_id = $videos_id; $obj->likes = 0; $obj->dislikes = 0; $obj->myVote = self::getMyVote($videos_id); $sql = "SELECT count(*) as total FROM likes WHERE videos_id = ? AND `like` = 1 "; // like - $res = sqlDAL::readSql($sql,"i",array($videos_id)); + $res = sqlDAL::readSql($sql, "i", array($videos_id)); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($global['mysqli']->errno!=0) { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->likes = intval($row['total']); $sql = "SELECT count(*) as total FROM likes WHERE videos_id = ? AND `like` = -1 "; // dislike - - $res = sqlDAL::readSql($sql,"i",array($videos_id)); + + $res = sqlDAL::readSql($sql, "i", array($videos_id)); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($global['mysqli']->errno!=0) { die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->dislikes = intval($row['total']); return $obj; } - - static function getTotalLikes() { + + public static function getTotalLikes() + { global $global; $obj = new stdClass(); $obj->likes = 0; $obj->dislikes = 0; $sql = "SELECT count(*) as total FROM likes WHERE `like` = 1 "; // like - $res = sqlDAL::readSql($sql); + $res = sqlDAL::readSql($sql); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!$res) { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->likes = intval($row['total']); $sql = "SELECT count(*) as total FROM likes WHERE `like` = -1 "; // dislike - $res = sqlDAL::readSql($sql); + $res = sqlDAL::readSql($sql); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!$res) { die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } $obj->dislikes = intval($row['total']); return $obj; } - static function getMyVote($videos_id) { + public static function getMyVote($videos_id) + { global $global; if (!User::isLogged()) { return 0; } $id = User::getId(); $sql = "SELECT `like` FROM likes WHERE videos_id = ? AND users_id = ? "; // like - - $res = sqlDAL::readSql($sql,"ii",array($videos_id,$id)); + + $res = sqlDAL::readSql($sql, "ii", array($videos_id,$id)); $dbLike = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($dbLike!=false) { return intval($dbLike['like']); } return 0; } - } diff --git a/objects/mysql_dal.php b/objects/mysql_dal.php index ee9ef9ed4..9642b693a 100644 --- a/objects/mysql_dal.php +++ b/objects/mysql_dal.php @@ -1,436 +1,436 @@ "; } OR while($row = sqlDAL::fetchAssoc($result)){ echo $row['user']."
"; } */ /* * Internal used class */ class iimysqli_result { public $stmt, $nCols, $fields; } global $disableMysqlNdMethods; // this is only to test both methods more easy. $disableMysqlNdMethods = false; /* * This class exists for making servers avaible, which have no mysqlnd, withouth cause a performance-issue for those who have the driver. * It wouldn't be possible without Daan on https://stackoverflow.com/questions/31562359/workaround-for-mysqlnd-missing-driver */ class sqlDAL { static function executeFile($filename) { global $global; $templine = ''; // Read in entire file $lines = file($filename); // Loop through each line foreach ($lines as $line) { // Skip it if it's a comment if (substr($line, 0, 2) == '--' || $line == '') continue; // Add this line to the current segment $templine .= $line; // If it has a semicolon at the end, it's the end of the query if (substr(trim($line), -1, 1) == ';') { // Perform the query if (!$global['mysqli']->query($templine)) { _error_log('sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

', AVideoLog::$ERROR); } // Reset temp variable to empty $templine = ''; } } } /* * For Sql like INSERT and UPDATE. The special point about this method: You do not need to close it (more direct). - * @param string $preparedStatement The Sql-command + * @param string $preparedStatement The Sql-command * @param string $formats i=int,d=doube,s=string,b=blob (http://www.php.net/manual/en/mysqli-stmt.bind-param.php) * @param array $values A array, containing the values for the prepared statement. * @return boolean true on success, false on fail */ static function writeSql($preparedStatement, $formats = "", $values = array()) { global $global, $disableMysqlNdMethods; // make sure it does not store autid transactions $debug = debug_backtrace(); if (empty($debug[2]['class']) || $debug[2]['class'] !== "AuditTable") { $audit = AVideoPlugin::loadPluginIfEnabled('Audit'); if (!empty($audit)) { try { $audit->exec(@$debug[1]['function'], @$debug[1]['class'], $preparedStatement, $formats, json_encode($values), User::getId()); } catch (Exception $exc) { echo log_error($exc->getTraceAsString()); } } } if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { log_error("[sqlDAL::writeSql] Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement})"); return false; } if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { log_error("[sqlDAL::writeSql] eval_mysql_bind failed: values and params in stmt don't match ({$preparedStatement}) with formats ({$formats})"); return false; } $stmt->execute(); if ($stmt->errno != 0) { log_error('Error in writeSql : (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); $stmt->close(); return false; } //$stmt->commit(); $stmt->close(); return true; } /* * For Sql like SELECT. This method needs to be closed anyway. If you start another readSql, while the old is open, it will fail. - * @param string $preparedStatement The Sql-command + * @param string $preparedStatement The Sql-command * @param string $formats i=int,d=doube,s=string,b=blob (http://www.php.net/manual/en/mysqli-stmt.bind-param.php) * @param array $values A array, containing the values for the prepared statement. * @return Object Depend if mysqlnd is active or not, a object, but always false on fail */ static function readSql($preparedStatement, $formats = "", $values = array(), $refreshCache = false) { // $refreshCache = true; global $global, $disableMysqlNdMethods, $readSqlCached, $crc; // need to add dechex because some times it return an negative value and make it fails on javascript playlists $crc = (md5($preparedStatement . implode($values))); if (!isset($readSqlCached)) { $readSqlCached = array(); } if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { // Mysqlnd enabled if ((!isset($readSqlCached[$crc])) || ($refreshCache)) { // When not cached $readSqlCached[$crc] = "false"; if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { log_error("[sqlDAL::readSql] (mysqlnd) Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement}) - format=({$formats}) values=" . json_encode($values)); log_error("[sqlDAL::readSql] trying close and reconnect"); $global['mysqli']->close(); _mysql_connect(); if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { log_error("[sqlDAL::readSql] (mysqlnd) Prepare failed again return false"); return false; } } if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { log_error("[sqlDAL::readSql] (mysqlnd) eval_mysql_bind failed: values and params in stmt don't match {$preparedStatement} with formats {$formats}"); return false; } $TimeLog = "[$preparedStatement], $formats, " . json_encode($values) . ", $refreshCache"; TimeLogStart($TimeLog); $stmt->execute(); $readSqlCached[$crc] = $stmt->get_result(); if ($stmt->errno != 0) { log_error('Error in readSql (mysqlnd): (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); $stmt->close(); $disableMysqlNdMethods = true; // try again with noMysqlND $read = self::readSql($preparedStatement, $formats, $values, $refreshCache); TimeLogEnd($TimeLog, "mysql_dal", 0.5); return $read; } TimeLogEnd($TimeLog, "mysql_dal", 0.5); $stmt->close(); } else if (is_object($readSqlCached[$crc])) { // When cached // reset the stmt for fetch. this solves objects/video.php line 550 $readSqlCached[$crc]->data_seek(0); //log_error("set dataseek to 0"); // increase a counter for the saved queries. if (isset($_SESSION['savedQuerys'])) { $_SESSION['savedQuerys']++; } } else { $readSqlCached[$crc] = "false"; } // // if ($readSqlCached[$crc] == "false") { - // add this in case the cache fail + // add this in case the cache fail // ->lenghts seems to be always NULL.. fix: $readSqlCached[$crc]->data_seek(0); above //if("SELECT * FROM configurations WHERE id = 1 LIMIT 1"==$preparedStatement){ // var_dump($readSqlCached[$crc]); //} if ($readSqlCached[$crc] != "false") { if (is_null($readSqlCached[$crc]->lengths) && !$refreshCache && $readSqlCached[$crc]->num_rows == 0 && $readSqlCached[$crc]->field_count == 0) { log_error("[sqlDAL::readSql] (mysqlnd) Something was going wrong, re-get the query. {$preparedStatement} {$readSqlCached[$crc]->num_rows}"); return self::readSql($preparedStatement, $formats, $values, true); } } else { $readSqlCached[$crc] = false; } // } } else { // Mysqlnd-fallback if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { log_error("[sqlDAL::readSql] (no mysqlnd) Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement})"); return false; } if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { log_error("[sqlDAL::readSql] (no mysqlnd) eval_mysql_bind failed: values and params in stmt don't match {$preparedStatement} with formats {$formats}"); return false; } $stmt->execute(); $result = self::iimysqli_stmt_get_result($stmt); if ($stmt->errno != 0) { log_error('Error in readSql (no mysqlnd): (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); $stmt->close(); $readSqlCached[$crc] = false; } else { $readSqlCached[$crc] = $result; } } return $readSqlCached[$crc]; } /* * This closes the readSql * @param Object $result A object from sqlDAL::readSql */ static function close($result) { global $disableMysqlNdMethods, $global; if ((!function_exists('mysqli_fetch_all')) || ($disableMysqlNdMethods != false)) { $result->stmt->close(); } } /* * Get the nr of rows * @param Object $result A object from sqlDAL::readSql * @return int The nr of rows */ static function num_rows($res) { global $global, $disableMysqlNdMethods, $crc, $num_row_cache; if (!isset($num_row_cache)) { $num_row_cache = array(); } // cache is working - but disable for proper test-results if (!isset($num_row_cache[$crc])) { if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { // Mysqlnd $num_row_cache[$crc] = 0; if (!empty($res->num_rows)) { $num_row_cache[$crc] = $res->num_rows; } return $num_row_cache[$crc]; } else { // Mysqlnd-fallback - use fetchAllAssoc because this can be cached. $num_row_cache[$crc] = sizeof(self::fetchAllAssoc($res)); } } return $num_row_cache[$crc]; } // unused static function cached_num_rows($data) { return sizeof($data); } /* * Make a fetch assoc on every row avaible * @param Object $result A object from sqlDAL::readSql * @return array A array filled with all rows as a assoc array */ static function fetchAllAssoc($result) { global $crc, $fetchAllAssoc_cache; if (!isset($fetchAllAssoc_cache)) { $fetchAllAssoc_cache = array(); } if (!isset($fetchAllAssoc_cache[$crc])) { $ret = array(); while ($row = self::fetchAssoc($result)) { $ret[] = $row; } $fetchAllAssoc_cache[$crc] = $ret; } return $fetchAllAssoc_cache[$crc]; } /* - * Make a single assoc fetch + * Make a single assoc fetch * @param Object $result A object from sqlDAL::readSql * @return int A single row in a assoc array */ static function fetchAssoc($result) { global $global, $disableMysqlNdMethods; ini_set('memory_limit', '-1'); // here, a cache is more/too difficult, because fetch gives always a next. with this kind of cache, we would give always the same. if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { if ($result != false) { return $result->fetch_assoc(); } } else { return self::iimysqli_result_fetch_assoc($result); } return false; } /* * Make a fetchArray on every row avaible * @param Object $result A object from sqlDAL::readSql * @return array A array filled with all rows */ static function fetchAllArray($result) { global $crc, $fetchAllArray_cache; if (!isset($fetchAllArray_cache)) { $fetchAllArray_cache = array(); } // cache is working - but disable for proper test-results if (!isset($fetchAllArray_cache[$crc])) { $ret = array(); while ($row = self::fetchArray($result)) { $ret[] = $row; } $fetchAllArray_cache[$crc] = $ret; } else { log_error("array-cache"); } return $fetchAllArray_cache[$crc]; } /* - * Make a single fetch + * Make a single fetch * @param Object $result A object from sqlDAL::readSql * @return int A single row in a array */ static function fetchArray($result) { global $global, $disableMysqlNdMethods; if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { return $result->fetch_array(); } else { return self::iimysqli_result_fetch_array($result); } return false; } private static function eval_mysql_bind($stmt, $formats, $values) { if (($stmt->param_count != sizeof($values)) || ($stmt->param_count != strlen($formats))) { return false; } if ((!empty($formats)) && (!empty($values))) { $code = "return \$stmt->bind_param(\"" . $formats . "\""; $i = 0; foreach ($values as $val) { $code .= ", \$values[" . $i . "]"; $i++; }; $code .= ");"; // echo $code. " : ".$preparedStatement; eval($code); } return true; } private static function iimysqli_stmt_get_result($stmt) { global $global; $metadata = mysqli_stmt_result_metadata($stmt); $ret = new iimysqli_result; $field_array = array(); if (!$metadata) { die("Execute query error, because: {$stmt->error}"); } $tmpFields = $metadata->fetch_fields(); $i = 0; foreach ($tmpFields as $f) { $field_array[$i] = $f->name; $i++; } $ret->fields = $field_array; if (!$ret) return NULL; $ret->nCols = mysqli_num_fields($metadata); $ret->stmt = $stmt; mysqli_free_result($metadata); return $ret; } private static function iimysqli_result_fetch_assoc(&$result) { global $global; $ret = array(); $code = "return mysqli_stmt_bind_result(\$result->stmt "; for ($i = 0; $i < $result->nCols; $i++) { $ret[$result->fields[$i]] = NULL; $code .= ", \$ret['" . $result->fields[$i] . "']"; }; $code .= ");"; if (!eval($code)) { return false; }; if (!mysqli_stmt_fetch($result->stmt)) { return false; }; return $ret; } private static function iimysqli_result_fetch_array(&$result) { $ret = array(); $code = "return mysqli_stmt_bind_result(\$result->stmt "; for ($i = 0; $i < $result->nCols; $i++) { $ret[$i] = NULL; $code .= ", \$ret['" . $i . "']"; }; $code .= ");"; if (!eval($code)) { return false; }; if (!mysqli_stmt_fetch($result->stmt)) { return false; }; return $ret; } } function log_error($err) { if (!empty($global['debug'])) { echo $err; } _error_log("MySQL ERROR: ".json_encode(debug_backtrace()), AVideoLog::$ERROR); _error_log($err, AVideoLog::$ERROR); } ?> diff --git a/objects/notifications.json.php b/objects/notifications.json.php index 0cf335ff9..b9c903fa7 100644 --- a/objects/notifications.json.php +++ b/objects/notifications.json.php @@ -1,31 +1,32 @@ $value) { $_POST[$key]=$value; } } -if(!empty($_POST['user']) && !empty($_POST['pass'])){ +if (!empty($_POST['user']) && !empty($_POST['pass'])) { $user = new User(0, $_POST['user'], $_POST['pass']); $user->login(false, true); } - $obj = new stdClass(); -if(AVideoPlugin::loadPluginIfEnabled("Live")){ +if (AVideoPlugin::loadPluginIfEnabled("Live")) { $liveStats = url_get_contents("{$global['webSiteRootURL']}plugin/Live/stats.json.php"); $obj->live = json_decode($liveStats); } -echo json_encode($obj); \ No newline at end of file +echo json_encode($obj); diff --git a/objects/notifySubscribers.json.php b/objects/notifySubscribers.json.php index f94dcc197..6ba278171 100644 --- a/objects/notifySubscribers.json.php +++ b/objects/notifySubscribers.json.php @@ -1,48 +1,48 @@ setFrom($config->getContactEmail()); //Set who the message is to be sent to //$mail->addAddress($config->getContactEmail()); foreach ($Subscribes as $value) { $mail->addBCC($value["email"]); } $obj->total = count($Subscribes); //Set the subject line $mail->Subject = 'Message From Site ' . $config->getWebSiteTitle(); $mail->msgHTML($_POST['message']); //send the message, check for errors if (!$mail->send()) { $obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo; } else { $obj->success = __("Message sent"); } echo json_encode($obj); diff --git a/objects/playListAddVideo.json.php b/objects/playListAddVideo.json.php index 565ba98c6..ed45f03bf 100644 --- a/objects/playListAddVideo.json.php +++ b/objects/playListAddVideo.json.php @@ -1,41 +1,40 @@ error = true; $obj->status = 0; if (!User::isLogged()) { $obj->msg = __("Permission denied"); die(json_encode($obj)); } - $plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists"); -if(empty($plugin)){ +if (empty($plugin)) { $obj->msg = "Plugin not enabled"; die(json_encode($obj)); } -if(!PlayLists::canAddVideoOnPlaylist($_POST['videos_id'])){ +if (!PlayLists::canAddVideoOnPlaylist($_POST['videos_id'])) { $obj->msg = "You can not add this video on playlist"; die(json_encode($obj)); } $playList = new PlayList($_POST['playlists_id']); -if(empty($playList || User::getId()!=$playList->getUsers_id()) || empty($_POST['videos_id'])){ +if (empty($playList || User::getId()!=$playList->getUsers_id()) || empty($_POST['videos_id'])) { $obj->msg = __("Permission denied"); die(json_encode($obj)); } $obj->error = false; $obj->status = $playList->addVideo($_POST['videos_id'], $_POST['add']); //log_error("videos id: ".$_POST['videos_id']." playlist_id: ".$_POST['playlists_id']); die(json_encode($obj)); diff --git a/objects/playlist.php b/objects/playlist.php index 65f69a5e3..f854075bc 100644 --- a/objects/playlist.php +++ b/objects/playlist.php @@ -1,612 +1,650 @@ setName($name); $row = self::getFromDbFromName($this->getName()); - if (empty($row)) + if (empty($row)) { return false; + } foreach ($row as $key => $value) { $this->$key = $value; } return true; } /** * * @global type $global * @param type $publicOnly * @param type $userId if not present check session * @param type $isVideoIdPresent pass the ID of the video checking * @return boolean */ - static function getAllFromUser($userId, $publicOnly = true, $status = false, $playlists_id = 0, $try = 0) { + public static function getAllFromUser($userId, $publicOnly = true, $status = false, $playlists_id = 0, $try = 0) + { global $global, $config, $refreshCacheFromPlaylist; $playlists_id = intval($playlists_id); $formats = ""; $values = array(); $sql = "SELECT u.*, pl.* FROM " . static::getTableName() . " pl " . " LEFT JOIN users u ON u.id = users_id WHERE 1=1 "; if (!empty($playlists_id)) { $sql .= " AND pl.id = '{$playlists_id}' "; } if (!empty($status)) { $status = str_replace("'", "", $status); $sql .= " AND pl.status = '{$status}' "; - } else - if ($publicOnly) { + } elseif ($publicOnly) { $sql .= " AND pl.status = 'public' "; } if (!empty($userId)) { $sql .= " AND users_id = ? "; $formats .= "i"; $values[] = $userId; } $sql .= self::getSqlFromPost("pl."); //echo $sql, $userId;exit; $res = sqlDAL::readSql($sql, $formats, $values, $refreshCacheFromPlaylist); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); $favorite = array(); $watch_later = array(); $favoriteCount = 0; $watch_laterCount = 0; if ($res != false) { foreach ($fullData as $row) { $row['videos'] = static::getVideosFromPlaylist($row['id']); $row['isFavorite'] = false; $row['isWatchLater'] = false; if ($row['status'] === "favorite") { $row['isFavorite'] = true; $favoriteCount++; $favorite = $row; - } else if ($row['status'] === "watch_later") { + } elseif ($row['status'] === "watch_later") { $watch_laterCount++; $row['isWatchLater'] = true; $watch_later = $row; } else { $rows[] = $row; } } if (!empty($userId)) { if ($try == 0 && ($favoriteCount > 1 || $watch_laterCount > 1)) { self::fixDuplicatePlayList($userId); $refreshCacheFromPlaylist = true; return self::getAllFromUser($userId, $publicOnly, $status, $playlists_id, $try + 1); } if (empty($_POST['current']) && empty($status) && $config->currentVersionGreaterThen("6.4")) { if (empty($favorite)) { $pl = new PlayList(0); $pl->setName("Favorite"); $pl->setStatus("favorite"); $pl->setUsers_id($userId); $id = $pl->save(); $refreshCacheFromPlaylist = true; $row['id'] = $id; $row['name'] = $pl->getName(); $row['status'] = $pl->getStatus(); $row['users_id'] = $pl->getUsers_id(); $favorite = $row; } if (empty($watch_later)) { $pl = new PlayList(0); $pl->setName("Watch Later"); $pl->setStatus("watch_later"); $pl->setUsers_id($userId); $id = $pl->save(); $refreshCacheFromPlaylist = true; $row['id'] = $id; $row['name'] = $pl->getName(); $row['status'] = $pl->getStatus(); $row['users_id'] = $pl->getUsers_id(); $watch_later = $row; } } } if (!empty($favorite)) { array_unshift($rows, $favorite); } if (!empty($watch_later)) { array_unshift($rows, $watch_later); } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - static function fixDuplicatePlayList($user_id) { + public static function fixDuplicatePlayList($user_id) + { if (empty($user_id)) { return false; } _error_log("PlayList::fixDuplicatePlayList Process user_id = {$user_id} favorite"); $sql = "SELECT * FROM playlists WHERE users_id = ? AND status = 'favorite' ORDER BY created "; $res = sqlDAL::readSql($sql, "i", array($user_id), true); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $key => $row) { if ($key === 0) { continue; } if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { _error_log("PlayList::fixDuplicatePlayList favorite PlayList NOT empty {$row['id']}"); continue; } $sql = "DELETE FROM playlists "; $sql .= " WHERE id = ?"; _error_log("PlayList::fixDuplicatePlayList favorite {$row['id']}"); sqlDAL::writeSql($sql, "i", array($row['id'])); } } _error_log("PlayList::fixDuplicatePlayList Process user_id = {$user_id} watch_later"); $sql = "SELECT * FROM playlists WHERE users_id = ? AND status = 'watch_later' ORDER BY created "; $res = sqlDAL::readSql($sql, "i", array($user_id), true); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $key => $row) { if ($key === 0) { continue; } if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { _error_log("PlayList::fixDuplicatePlayList watch_later PlayList NOT empty {$row['id']}"); continue; } $sql = "DELETE FROM playlists "; $sql .= " WHERE id = ?"; _error_log("PlayList::fixDuplicatePlayList watch_later {$row['id']}"); ob_flush(); sqlDAL::writeSql($sql, "i", array($row['id'])); } } } - static function getAllFromUserVideo($userId, $videos_id, $publicOnly = true, $status = false) { + public static function getAllFromUserVideo($userId, $videos_id, $publicOnly = true, $status = false) + { if (empty($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)])) { $rows = self::getAllFromUser($userId, $publicOnly, $status); foreach ($rows as $key => $value) { $videos = self::getVideosIdFromPlaylist($value['id']); $rows[$key]['isOnPlaylist'] = in_array($videos_id, $videos); } _session_start(); $_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)] = $rows; } else { $rows = $_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)]; } return $rows; } - static private function removeCache($videos_id) { + private static function removeCache($videos_id) + { $close = false; _session_start(); unset($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id]); unset($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id]); } - static function getVideosIDFromPlaylistLight($playlists_id) { + public static function getVideosIDFromPlaylistLight($playlists_id) + { global $global; $sql = "SELECT * FROM playlists_has_videos p WHERE playlists_id = ? ORDER BY `order` "; - /* + /* cleanSearchVar(); $sort = @$_POST['sort']; $_POST['sort'] = array(); $sql .= self::getSqlFromPost(); $_POST['sort'] = $sort; reloadSearchVar(); - * - */ + * + */ $res = sqlDAL::readSql($sql, "i", array($playlists_id)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - public static function setCache($name, $value) { + public static function setCache($name, $value) + { parent::setCache($name, $value); } - static function getVideosFromPlaylist($playlists_id) { + public static function getVideosFromPlaylist($playlists_id) + { $sql = "SELECT *,v.created as cre, p.`order` as video_order, v.externalOptions as externalOptions " . ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes " . " FROM playlists_has_videos p " . " LEFT JOIN videos as v ON videos_id = v.id " . " LEFT JOIN users u ON u.id = v.users_id " . " WHERE playlists_id = ? AND v.status != 'i' "; cleanSearchVar(); $sort = @$_POST['sort']; $_POST['sort'] = array(); $_POST['sort']['p.`order`'] = 'ASC'; $sql .= self::getSqlFromPost(); reloadSearchVar(); $_POST['sort'] = $sort; $cacheName = "getVideosFromPlaylist{$playlists_id}".md5($sql); $rows = self::getCache($cacheName, 0); if (empty($rows)) { global $global; $res = sqlDAL::readSql($sql, "i", array($playlists_id)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); $SubtitleSwitcher = AVideoPlugin::loadPluginIfEnabled("SubtitleSwitcher"); if ($res != false) { $timeLog2 = __FILE__ . " - getVideosFromPlaylist: {$playlists_id}"; TimeLogStart($timeLog2); foreach ($fullData as $row) { if (!empty($_GET['isChannel'])) { $row['tags'] = Video::getTags($row['id']); $row['pluginBtns'] = AVideoPlugin::getPlayListButtons($playlists_id); $row['humancreate'] = humanTiming(strtotime($row['cre'])); } TimeLogEnd($timeLog2, __LINE__); $images = Video::getImageFromFilename($row['filename'], $row['type']); TimeLogEnd($timeLog2, __LINE__); $row['images'] = $images; $row['videos'] = Video::getVideosPaths($row['filename'], true); TimeLogEnd($timeLog2, __LINE__); $row['progress'] = Video::getVideoPogressPercent($row['videos_id']); TimeLogEnd($timeLog2, __LINE__); $row['title'] = UTF8encode($row['title']); TimeLogEnd($timeLog2, __LINE__); $row['description'] = UTF8encode($row['description']); TimeLogEnd($timeLog2, __LINE__); $row['tags'] = Video::getTags($row['videos_id']); TimeLogEnd($timeLog2, __LINE__); if (AVideoPlugin::isEnabledByName("VideoTags")) { $row['videoTags'] = Tags::getAllFromVideosId($row['videos_id']); $row['videoTagsObject'] = Tags::getObjectFromVideosId($row['videos_id']); } TimeLogEnd($timeLog2, __LINE__); if ($SubtitleSwitcher) { $row['subtitles'] = getVTTTracks($row['filename'], true); foreach ($row['subtitles'] as $value) { $row['subtitlesSRT'][] = convertSRTTrack($value); } } TimeLogEnd($timeLog2, __LINE__); unset($row['password']); unset($row['recoverPass']); //unset($row['description']); $rows[] = $row; } self::setCache($cacheName, $rows); } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } else { $rows = object_to_array($rows); } return $rows; } - static function isVideoOnFavorite($videos_id, $users_id) { + public static function isVideoOnFavorite($videos_id, $users_id) + { return self::isVideoOn($videos_id, $users_id, 'favorite'); } - static function isVideoOnWatchLater($videos_id, $users_id) { + public static function isVideoOnWatchLater($videos_id, $users_id) + { return self::isVideoOn($videos_id, $users_id, 'watch_later'); } - private static function isVideoOn($videos_id, $users_id, $status) { + private static function isVideoOn($videos_id, $users_id, $status) + { global $global; $status = str_replace("'", "", $status); $sql = "SELECT pl.id FROM " . static::getTableName() . " pl " . " LEFT JOIN users u ON u.id = users_id " . " LEFT JOIN playlists_has_videos p ON pl.id = playlists_id" . " LEFT JOIN videos as v ON videos_id = v.id " . " WHERE videos_id = ? AND pl.users_id = ? AND pl.status = '{$status}' LIMIT 1 "; //echo $videos_id," - " ,$users_id, $sql; $res = sqlDAL::readSql($sql, "ii", array($videos_id, $users_id)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } - static function getFavoriteIdFromUser($users_id) { + public static function getFavoriteIdFromUser($users_id) + { global $refreshCacheFromPlaylist; $favorite = self::getIdFromUser($users_id, "favorite"); if (empty($favorite)) { $pl = new PlayList(0); $pl->setName("Favorite"); $pl->setUsers_id($users_id); $pl->setStatus("favorite"); $pl->save(); $refreshCacheFromPlaylist = true; $favorite = self::getIdFromUser($users_id, "favorite"); } return $favorite; } - static function getWatchLaterIdFromUser($users_id) { + public static function getWatchLaterIdFromUser($users_id) + { global $refreshCacheFromPlaylist; $watch_later = self::getIdFromUser($users_id, "watch_later"); if (empty($watch_later)) { $pl = new PlayList(0); $pl->setName("Watch Later"); $pl->setUsers_id($users_id); $pl->setStatus("watch_later"); $pl->save(); $refreshCacheFromPlaylist = true; $watch_later = self::getIdFromUser($users_id, "watch_later"); } return $watch_later; } - private static function getIdFromUser($users_id, $status) { + private static function getIdFromUser($users_id, $status) + { global $global; $status = str_replace("'", "", $status); $sql = "SELECT * FROM " . static::getTableName() . " pl WHERE" . " users_id = ? AND pl.status = '{$status}' LIMIT 1 "; $res = sqlDAL::readSql($sql, "i", array($users_id)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res && !empty($data)) { $row = $data['id']; } else { $row = false; } return $row; } - static function getVideosIdFromPlaylist($playlists_id) { + public static function getVideosIdFromPlaylist($playlists_id) + { global $getVideosIdFromPlaylist; - if(empty($getVideosIdFromPlaylist)){ + if (empty($getVideosIdFromPlaylist)) { $getVideosIdFromPlaylist = array(); } - if(isset($getVideosIdFromPlaylist[$playlists_id])){ + if (isset($getVideosIdFromPlaylist[$playlists_id])) { return $getVideosIdFromPlaylist[$playlists_id]; } $videosId = array(); $rows = static::getVideosIDFromPlaylistLight($playlists_id); foreach ($rows as $value) { $videosId[] = $value['videos_id']; } - + $getVideosIdFromPlaylist[$playlists_id] = $videosId; return $videosId; } - static function sortVideos($videosList, $listIdOrder) { + public static function sortVideos($videosList, $listIdOrder) + { $list = array(); foreach ($listIdOrder as $value) { $found = false; foreach ($videosList as $key => $value2) { if ($value2['id'] == $value) { $list[] = $value2; unset($videosList[$key]); $found = true; } } if (!$found) { $v = new Video("", "", $value); if (empty($v->getFilename())) { continue; } $list[] = array('id' => $value); } } return $list; } - public function save() { + public function save() + { if (!User::isLogged()) { return false; } $this->clearEmptyLists(); $users_id = User::getId(); $this->setUsers_id($users_id); $this->showOnTV = intval($this->showOnTV); $playlists_id = parent::save(); if (!empty($playlists_id)) { self::deleteCache("getVideosFromPlaylist{$playlists_id}"); } return $playlists_id; } /** * This is just to fix errors from the update 6.4 to 6.5, where empty playlists were created before the update * @return type */ - private function clearEmptyLists() { + private function clearEmptyLists() + { $sql = "DELETE FROM " . static::getTableName() . " WHERE status = ''"; return sqlDAL::writeSql($sql); } - public function addVideo($videos_id, $add, $order = 0) { + public function addVideo($videos_id, $add, $order = 0) + { global $global; $formats = ""; $values = array(); if (empty($add) || $add === "false") { $sql = "DELETE FROM playlists_has_videos WHERE playlists_id = ? AND videos_id = ? "; $formats = "ii"; $values[] = $this->id; $values[] = $videos_id; } else { $this->addVideo($videos_id, false); $sql = "INSERT INTO playlists_has_videos ( playlists_id, videos_id , `order`) VALUES (?, ?, ?) "; $formats = "iii"; $values[] = $this->id; $values[] = $videos_id; $values[] = $order; } self::deleteCache("getVideosFromPlaylist{$this->id}"); self::removeCache($videos_id); return sqlDAL::writeSql($sql, $formats, $values); } - public function delete() { + public function delete() + { if (empty($this->id)) { return false; } self::deleteCache("getVideosFromPlaylist{$this->id}"); global $global; $sql = "DELETE FROM playlists WHERE id = ? "; //echo $sql; return sqlDAL::writeSql($sql, "i", array($this->id)); } - function getId() { + public function getId() + { return $this->id; } - function getName() { + public function getName() + { return $this->name; } - function getModified() { + public function getModified() + { return $this->modified; } - function getUsers_id() { + public function getUsers_id() + { return $this->users_id; } - function getStatus() { + public function getStatus() + { return $this->status; } - function setId($id) { + public function setId($id) + { $this->id = $id; } - function setName($name) { - if (strlen($name) > 45) + public function setName($name) + { + if (strlen($name) > 45) { $name = substr($name, 0, 42) . '...'; + } $this->name = xss_esc($name); //var_dump($name,$this->name);exit; } - function setUsers_id($users_id) { + public function setUsers_id($users_id) + { $this->users_id = $users_id; } - function setStatus($status) { + public function setStatus($status) + { if (!in_array($status, self::$validStatus)) { $status = 'public'; } $this->status = $status; } - static function canSee($playlist_id, $users_id) { + public static function canSee($playlist_id, $users_id) + { $obj = new PlayList($playlist_id); $status = $obj->getStatus(); if ($status !== 'public' && $status !== 'unlisted' && $users_id != $obj->getUsers_id()) { return false; } return true; } - - static function getEPG(){ + + public static function getEPG() + { global $config, $global; $encoder = $config->_getEncoderURL(); $url = "{$encoder}view/videosListEPG.php?date_default_timezone=". urlencode(date_default_timezone_get()); $content = url_get_contents($url); return json_decode($content); } - - function getShowOnTV() { + + public function getShowOnTV() + { return intval($this->showOnTV); } - function setShowOnTV($showOnTV) { - if(strtolower($showOnTV)==="false"){ + public function setShowOnTV($showOnTV) + { + if (strtolower($showOnTV)==="false") { $showOnTV = 0; - }else if(strtolower($showOnTV)==="true"){ + } elseif (strtolower($showOnTV)==="true") { $showOnTV = 1; } $this->showOnTV = intval($showOnTV); } - - - static function getAllToShowOnTV() { + public static function getAllToShowOnTV() + { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT u.*, pl.* FROM playlists pl " . " LEFT JOIN users u ON users_id = u.id " . " WHERE showOnTV=1 "; $sql .= self::getSqlFromPost(); //echo $sql;exit; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - } diff --git a/objects/playlistSort.php b/objects/playlistSort.php index f1adf1a53..7736d0f21 100644 --- a/objects/playlistSort.php +++ b/objects/playlistSort.php @@ -1,95 +1,96 @@ getUsers_id()){ +if (User::getId() != $obj->getUsers_id()) { die('{"error":"'.__("Permission denied").'"}'); } $count = 1; -if(empty($_POST['list'])){ +if (empty($_POST['list'])) { // get all videos from playlist $videosArrayId = PlayList::getVideosIdFromPlaylist($_POST['playlist_id']); - $videos = array(); + $videos = array(); foreach ($videosArrayId as $value) { $videos[] = Video::getVideoLight($value); } $sortFunc = "titleASC"; switch ($_GET['sort']) { case 1: $sortFunc = "titleASC"; break; case 2: $sortFunc = "titleDESC"; break; case 3: $sortFunc = "dateCmp"; break; case 4: $sortFunc = "dateCmpDesc"; break; } //var_dump($sortFunc);exit; // sort video uasort($videos, $sortFunc); - + // transfer the id to the list foreach ($videos as $key => $value) { $_POST['list'][] = $value['id']; } - } - foreach ($_POST['list'] as $key => $value) { $result = $obj->addVideo($value, true, $count++); } -if(!empty($_GET['sort'])){ +if (!empty($_GET['sort'])) { header("Location: ". $_SERVER['HTTP_REFERER']); //header("Location: ". User::getChannelLink($obj->getUsers_id())); exit; } $o = new stdClass(); $o->status = $result; //$o->channelName = $obj->get; echo json_encode($o);exit; - // Comparison function -function dateCmp($videoA, $videoB) { +function dateCmp($videoA, $videoB) +{ $a = strtotime($videoA['created']); $b = strtotime($videoB['created']); if ($a == $b) { return 0; } return ($a > $b) ? -1 : 1; } -function dateCmpDesc($videoA, $videoB) { +function dateCmpDesc($videoA, $videoB) +{ $a = strtotime($videoA['created']); $b = strtotime($videoB['created']); if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } -function titleASC($videoA, $videoB) { +function titleASC($videoA, $videoB) +{ return strcasecmp($videoA['title'], $videoB['title']); } -function titleDESC($videoA, $videoB) { +function titleDESC($videoA, $videoB) +{ return strcasecmp($videoB['title'], $videoA['title']); } diff --git a/objects/playlists.json.php b/objects/playlists.json.php index a2228d075..69d05a197 100644 --- a/objects/playlists.json.php +++ b/objects/playlists.json.php @@ -1,18 +1,18 @@ $value) { foreach ($row[$key]['videos'] as $key2 => $value2) { - unset($row[$key]['videos'][$key2]['description']); + unset($row[$key]['videos'][$key2]['description']); } } echo json_encode($row); diff --git a/objects/playlistsFromUserVideos.json.php b/objects/playlistsFromUserVideos.json.php index 9bf210774..fd2a1c703 100644 --- a/objects/playlistsFromUserVideos.json.php +++ b/objects/playlistsFromUserVideos.json.php @@ -1,22 +1,21 @@ $value) { $_POST[$key]=$value; } } if(!empty($_POST['user']) && !empty($_POST['pass'])){ $user = new User(0, $_POST['user'], $_POST['pass']); $user->login(false, true); } if(empty($_POST['playlists_id'])){ die('Play List can not be empty'); } require_once './playlist.php'; $videos = PlayList::getVideosFromPlaylist($_POST['playlists_id']); $objMob = AVideoPlugin::getObjectData("MobileManager"); foreach ($videos as $key => $value) { unset($videos[$key]['password']); unset($videos[$key]['recoverPass']); $images = Video::getImageFromFilename($videos[$key]['filename'], $videos[$key]['type']); $videos[$key]['images'] = $images; $videos[$key]['Poster'] = !empty($objMob->portraitImage)?$images->posterPortrait:$images->poster; $videos[$key]['Thumbnail'] = !empty($objMob->portraitImage)?$images->posterPortraitThumbs:$images->thumbsJpg; $videos[$key]['imageClass'] = !empty($objMob->portraitImage)?"portrait":"landscape"; $videos[$key]['VideoUrl'] = getVideosURL($videos[$key]['filename']); $videos[$key]['createdHumanTiming'] = humanTiming(strtotime($videos[$key]['created'])); $videos[$key]['pageUrl'] = "{$global['webSiteRootURL']}video/".$videos[$key]['clean_title']; $videos[$key]['embedUrl'] = "{$global['webSiteRootURL']}videoEmbeded/".$videos[$key]['clean_title']; unset($_POST['sort']); unset($_POST['current']); unset($_POST['searchPhrase']); $_REQUEST['rowCount'] = 10; $_POST['sort']['created'] = "desc"; $videos[$key]['comments'] = Comment::getAllComments($videos[$key]['id']); $videos[$key]['commentsTotal'] = Comment::getTotalComments($videos[$key]['id']); foreach ($videos[$key]['comments'] as $key2 => $value2) { $user = new User($value2['users_id']); $videos[$key]['comments'][$key2]['userPhotoURL'] = User::getPhoto($videos[$key]['comments'][$key2]['users_id']); $videos[$key]['comments'][$key2]['userName'] = $user->getNameIdentificationBd(); } $videos[$key]['subscribers'] = Subscribe::getTotalSubscribes($videos[$key]['users_id']); - + $videos[$key]['firstVideo'] = ""; foreach ($videos[$key]['VideoUrl'] as $value2) { if($value2["type"] === 'video'){ $videos[$key]['firstVideo'] = $value2["url"]; break; - } + } } if(preg_match("/^videos/", $videos[$key]['photoURL'])){ $videos[$key]['UserPhoto'] = "{$global['webSiteRootURL']}".$videos[$key]['photoURL']; }else{ $videos[$key]['UserPhoto'] = $videos[$key]['photoURL']; } - + } echo json_encode($videos); diff --git a/objects/plugin.php b/objects/plugin.php index d552bf9b0..6db512630 100644 --- a/objects/plugin.php +++ b/objects/plugin.php @@ -1,539 +1,539 @@ id; } function getStatus() { return $this->status; } function getObject_data() { return $this->object_data; } function getPluginVersion() { return $this->pluginVersion; } function getName() { return $this->name; } function setId($id) { $this->id = $id; } function setStatus($status) { $this->status = $status; } function setObject_data($object_data) { $this->object_data = $object_data; } function setName($name) { $name = preg_replace("/[^A-Za-z0-9 _-]/", '', $name); $this->name = $name; } function getUuid() { return $this->uuid; } function getDirName() { return $this->dirName; } function setUuid($uuid) { $this->uuid = $uuid; $this->loadFromUUID($uuid); } function setDirName($dirName) { $dirName = preg_replace("/[^A-Za-z0-9 _-]/", '', $dirName); $this->dirName = $dirName; } function setPluginversion($pluginversion) { $this->pluginversion = $pluginversion; } static function setCurrentVersionByUuid($uuid, $currentVersion) { _error_log("plugin::setCurrentVersionByUuid $uuid, $currentVersion"); $p = static::getPluginByUUID($uuid); if (!$p) { _error_log("plugin::setCurrentVersionByUuid error on get plugin"); return false; } //pluginversion isn't an object property so we must explicity update it using this function $sql = "update " . static::getTableName() . " set pluginversion='$currentVersion' where uuid='$uuid'"; $name = "plugin$uuid"; ObjectYPT::deleteCache($name); $res = sqlDal::writeSql($sql); } static function getCurrentVersionByUuid($uuid) { $p = static::getPluginByUUID($uuid); if (!$p) return false; //pluginversion isn't an object property so we must explicity update it using this function $sql = "SELECT pluginversion FROM " . static::getTableName() . " WHERE uuid=? LIMIT 1 "; $res = sqlDAL::readSql($sql, "s", array($uuid)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { return $data['pluginversion']; } return false; } static function getPluginByName($name) { global $global, $getPluginByName; if (empty($getPluginByName)) { $getPluginByName = array(); } if (empty($getPluginByName[$name])) { $sql = "SELECT * FROM " . static::getTableName() . " WHERE name = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($name), true); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { $getPluginByName[$name] = $data; } else { $getPluginByName[$name] = false; } } return $getPluginByName[$name]; } static function getPluginByUUID($uuid) { global $global, $getPluginByUUID, $pluginJustInstalled; $name = "plugin$uuid"; if (!isset($getPluginByUUID)) { $getPluginByUUID = array(); } if (!isset($pluginJustInstalled)) { $pluginJustInstalled = array(); } if (empty($getPluginByUUID[$uuid])) { $getPluginByUUID[$uuid] = object_to_array(ObjectYPT::getCache($name, 0)); } if (empty($getPluginByUUID[$uuid])) { $sql = "SELECT * FROM " . static::getTableName() . " WHERE uuid = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($uuid)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { if (empty($data['pluginversion'])) { $data['pluginversion'] = "1.0"; } if (AVideoPlugin::isPluginOnByDefault($uuid)) { $data['status'] = 'active'; } $getPluginByUUID[$uuid] = $data; ObjectYPT::setCache($name, $getPluginByUUID[$uuid]); } else { $name = AVideoPlugin::getPluginsNameOnByDefaultFromUUID($uuid); if ($name !== false && empty($pluginJustInstalled[$uuid])) { $pluginJustInstalled[$uuid] = 1; _error_log("plugin::getPluginByUUID {$name} {$uuid} this plugin is On By Default we will install it ($sql)"); self::deleteByUUID($uuid); self::deleteByName($name); unset($getPluginByUUID[$uuid]); $getPluginByUUID[$uuid] = self::getOrCreatePluginByName($name, 'active'); } else { $getPluginByUUID[$uuid] = false; } } } return $getPluginByUUID[$uuid]; } function loadFromUUID($uuid) { $uuid = preg_replace("/[^A-Za-z0-9 _-]/", '', $uuid); $this->uuid = $uuid; $row = static::getPluginByUUID($uuid); if (!empty($row)) { $this->load($row['id']); } } static function isEnabledByName($name) { $row = static::getPluginByName($name); if ($row) { return $row['status'] == 'active' && AVideoPlugin::isPluginTablesInstalled($name, true); } return false; } static function isEnabledByUUID($uuid) { $row = static::getPluginByUUID($uuid); if ($row) { return $row['status'] == 'active' && AVideoPlugin::isPluginTablesInstalled($row['name'], true); } return false; } static function getAvailablePlugins($comparePluginVersion = false) { global $global, $getAvailablePlugins; $pluginsMarketplace = array(); if ($comparePluginVersion) { $pluginsMarketplace = ObjectYPT::getSessionCache('getAvailablePlugins', 600); // 10 min cache if (empty($pluginsMarketplace)) { $pluginsMarketplace = json_decode(url_get_contents("https://tutorials.avideo.com/info?version=1", "", 2)); ObjectYPT::setSessionCache('getAvailablePlugins', $pluginsMarketplace); } } if (empty($getAvailablePlugins)) { $dir = $global['systemRootPath'] . "plugin"; $getAvailablePlugins = array(); $cdir = scandir($dir); foreach ($cdir as $key => $value) { if (!in_array($value, array(".", ".."))) { if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { $p = AVideoPlugin::loadPlugin($value); if (!is_object($p) || $p->hidePlugin()) { if ($value !== "Statistics") { // avoid error while this plugin is not ready _error_log("Plugin Not Found: {$value}"); } continue; } $obj = new stdClass(); $obj->name = $p->getName(); $obj->dir = $value; $obj->uuid = $p->getUUID(); $obj->description = $p->getDescription(); $obj->installedPlugin = static::getPluginByUUID($obj->uuid); $obj->enabled = (!empty($obj->installedPlugin['status']) && $obj->installedPlugin['status'] === "active") ? true : false; $obj->id = (!empty($obj->installedPlugin['id'])) ? $obj->installedPlugin['id'] : 0; $obj->data_object = $p->getDataObject(); $obj->data_object_helper = $p->getDataObjectHelper(); $obj->databaseScript = !empty(static::getDatabaseFile($value)); $obj->pluginMenu = $p->getPluginMenu(); $obj->tags = $p->getTags(); $obj->pluginversion = $p->getPluginVersion(); $obj->pluginversionMarketPlace = (!empty($pluginsMarketplace->plugins->{$obj->uuid}) ? $pluginsMarketplace->plugins->{$obj->uuid}->pluginversion : 0); $obj->pluginversionCompare = (!empty($obj->pluginversionMarketPlace) ? version_compare($obj->pluginversion, $obj->pluginversionMarketPlace) : 0); $obj->permissions = $obj->enabled ? Permissions::getPluginPermissions($obj->id) : array(); $obj->isPluginTablesInstalled = AVideoPlugin::isPluginTablesInstalled($obj->name, false); if ($obj->pluginversionCompare < 0) { $obj->tags[] = "update"; } $getAvailablePlugins[] = $obj; } } } } return $getAvailablePlugins; } static function getAvailablePluginsBasic() { global $global, $getAvailablePlugins; if (empty($getAvailablePlugins)) { $dir = $global['systemRootPath'] . "plugin"; $getAvailablePlugins = array(); $cdir = scandir($dir); foreach ($cdir as $key => $value) { if (!in_array($value, array(".", ".."))) { if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { $p = AVideoPlugin::loadPlugin($value); if (!is_object($p) || $p->hidePlugin()) { if ($value !== "Statistics") { // avoid error while this plugin is not ready _error_log("Plugin Not Found: {$value}"); } continue; } $obj = new stdClass(); $obj->name = $p->getName(); $obj->pluginversion = $p->getPluginVersion(); $getAvailablePlugins[$p->getUUID()] = $obj; } } } } return $getAvailablePlugins; } static function getDatabaseFile($pluginName) { $filename = static::getDatabaseFileName($pluginName); if (!$filename) { return false; } return url_get_contents($filename); } static function getDatabaseFileName($pluginName) { global $global; $pluginName = AVideoPlugin::fixName($pluginName); $dir = $global['systemRootPath'] . "plugin"; $filename = $dir . DIRECTORY_SEPARATOR . $pluginName . DIRECTORY_SEPARATOR . "install" . DIRECTORY_SEPARATOR . "install.sql"; if (!file_exists($filename)) { return false; } return $filename; } static function getAllEnabled($try = 0) { global $global, $getAllEnabledRows; if (empty($getAllEnabledRows)) { $getAllEnabledRows = ObjectYPT::getCache("plugin::getAllEnabled", 3600); $getAllEnabledRows = object_to_array($getAllEnabledRows); if (empty($getAllEnabledRows)) { $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='active' "; $defaultEnabledUUIDs = AVideoPlugin::getPluginsOnByDefault(true); $defaultEnabledNames = AVideoPlugin::getPluginsOnByDefault(false); $sql .= " OR uuid IN ('" . implode("','", $defaultEnabledUUIDs) . "')"; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $getAllEnabledRows = array(); foreach ($fullData as $row) { $getAllEnabledRows[] = $row; if (($key = array_search($row['uuid'], $defaultEnabledUUIDs)) !== false) { unset($defaultEnabledUUIDs[$key]); unset($defaultEnabledNames[$key]); } } $addedNewPlugin = false; foreach ($defaultEnabledUUIDs as $key => $value) { $obj = new Plugin(0); $obj->loadFromUUID($defaultEnabledUUIDs[$key]); $obj->setName($defaultEnabledNames[$key]); $obj->setDirName($defaultEnabledNames[$key]); $obj->setStatus("active"); if ($obj->save()) { $addedNewPlugin = true; } } if ($addedNewPlugin && empty($try)) { ObjectYPT::deleteALLCache(); return self::getAllEnabled(1); } uasort($getAllEnabledRows, 'cmpPlugin'); ObjectYPT::setCache("plugin::getAllEnabled", $getAllEnabledRows); } } return $getAllEnabledRows; } static function getAllDisabled() { global $global, $getAllDisabledRows; if (empty($getAllDisabledRows)) { $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='inactive' "; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $getAllDisabledRows = array(); foreach ($fullData as $row) { $getAllDisabledRows[] = $row; } uasort($getAllDisabledRows, 'cmpPlugin'); } return $getAllDisabledRows; } static function getEnabled($uuid) { global $global, $getEnabled; if (empty($getEnabled)) { $getEnabled = array(); } if (in_array($uuid, AVideoPlugin::getPluginsOnByDefault())) { // make sure the OnByDefault plugins are enabled return self::getOrCreatePluginByName(AVideoPlugin::getPluginsNameOnByDefaultFromUUID($uuid)); } if (empty($getEnabled[$uuid])) { $getEnabled[$uuid] = array(); $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='active' AND uuid = '" . $uuid . "' ;"; $res = sqlDAL::readSql($sql); $pluginRows = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($pluginRows != false) { foreach ($pluginRows as $row) { $getEnabled[$uuid][] = $row; } } } return $getEnabled[$uuid]; } static function deleteByUUID($uuid) { global $global; $uuid = $global['mysqli']->real_escape_string($uuid); if (!empty($uuid)) { _error_log("Plugin:deleteByUUID {$uuid}"); $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE uuid = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "s", array($uuid)); } return false; } static function deleteByName($name) { global $global; $name = $global['mysqli']->real_escape_string($name); if (!empty($name)) { _error_log("Plugin:deleteByName {$name}"); $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE name = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "s", array($name)); } return false; } static function getOrCreatePluginByName($name, $statusIfCreate = 'inactive') { global $global; if (self::getPluginByName($name) === false) { $pluginFile = $global['systemRootPath'] . "plugin/{$name}/{$name}.php"; if (file_exists($pluginFile)) { require_once $pluginFile; $code = "\$p = new {$name}();"; eval($code); $plugin = new Plugin(0); $plugin->setUuid($p->getUUID()); $plugin->setDirName($name); $plugin->setName($name); $plugin->setObject_data(json_encode($p->getDataObject())); $plugin->setStatus($statusIfCreate); $plugin->setPluginversion($p->getPluginVersion()); $plugin->save(); } } return self::getPluginByName($name); } function save() { if (empty($this->uuid)) { return false; } global $global; $this->object_data = $global['mysqli']->real_escape_string($this->object_data); if (empty($this->object_data)) { $this->object_data = 'null'; } self::deletePluginCache($this->uuid); ObjectYPT::deleteALLCache(); return parent::save(); } - + static function deletePluginCache($uuid){ $name = "plugin{$uuid}"; ObjectYPT::deleteCache($name); ObjectYPT::deleteCache("plugin::getAllEnabled"); } static function encryptIfNeed($object_data) { $isString = false; if (!is_object($object_data)) { $object_data = json_decode($object_data); $isString = true; } if (!empty($object_data)) { foreach ($object_data as $key => $value) { if (!empty($value->type) && !empty($value->value) && is_string($value->type) && strtolower($value->type) === "encrypted") { if (!self::isEncrypted($value->value)) { $obj2 = new stdClass(); $obj2->dateEncrypted = time(); $obj2->value = $value->value; $object_data->$key->value = encryptString($obj2); } } } if ($isString) { $object_data = json_encode($object_data); } return $object_data; } else { return ''; } } static function decryptIfNeed($object_data) { $isString = false; if (!is_object($object_data)) { $object_data = json_decode($object_data); $isString = true; } if (!empty($object_data)) { foreach ($object_data as $key => $value) { if (!empty($value->type) && !empty($value->value) && strtolower($value->type) === "encrypted") { $isEncrypted = self::isEncrypted($value->value); if ($isEncrypted) { $object_data->$key->value = $isEncrypted; } } } if ($isString) { $object_data = json_encode($object_data); } return $object_data; } else { return ''; } } static function isEncrypted($object_data_element_value) { if (!empty($object_data_element_value)) { $object_data_element_value_json = decryptString($object_data_element_value); $object_data_element_value_json = json_decode($object_data_element_value_json); if (!empty($object_data_element_value_json) && !empty($object_data_element_value_json->dateEncrypted)) { return $object_data_element_value_json->value; } } return false; } } class PluginTags { static $RECOMMENDED = array('success', 'Recommended', '', 'RECOMMENDED'); static $SECURITY = array('warning', 'Security', '', 'SECURITY'); static $LIVE = array('primary', 'Live', '', 'LIVE'); static $MONETIZATION = array('primary', 'Monetization', '', 'MONETIZATION'); static $ADS = array('primary', 'ADS', '', 'ADS'); static $STORAGE = array('primary', 'Storage', '', 'STORAGE'); static $GALLERY = array('primary', 'Gallery', '', 'GALLERY'); static $NETFLIX = array('primary', 'Netflix', '', 'NETFLIX'); static $LAYOUT = array('primary', 'Layout', '', 'LAYOUT'); static $LOGIN = array('primary', 'Login', '', 'LOGIN'); static $MOBILE = array('primary', 'Mobile', '', 'MOBILE'); static $PLAYER = array('primary', 'Player', '', 'PLAYER'); static $FREE = array('info', 'Free', '', 'FREE'); static $PREMIUM = array('info', 'Premium', '', 'PREMIUM'); static $DEPRECATED = array('danger', 'Deprecated', '', 'DEPRECATED'); } diff --git a/objects/pluginAddDataObject.json.php b/objects/pluginAddDataObject.json.php index 84e5ad88f..38987dd0d 100644 --- a/objects/pluginAddDataObject.json.php +++ b/objects/pluginAddDataObject.json.php @@ -1,23 +1,23 @@ setObject_data(addcslashes($_POST['object_data'],'\\')); echo '{"status":"'.$obj->save().'"}'; \ No newline at end of file diff --git a/objects/pluginImport.json.php b/objects/pluginImport.json.php index 3c5157093..2ce1741a0 100644 --- a/objects/pluginImport.json.php +++ b/objects/pluginImport.json.php @@ -1,44 +1,44 @@ uploaded = false; $obj->filename = $_FILES['input-b1']['name']; if (!empty($global['disableAdvancedConfigurations'])) { die(json_encode($obj)); } if (!User::isAdmin()) { $obj->msg = "You are not admin"; die(json_encode($obj)); } $allowed = array('zip'); $path_parts = pathinfo($_FILES['input-b1']['name']); $extension = $path_parts['extension']; if (!in_array(strtolower($extension), $allowed)) { $obj->msg = "File extension error (" . $_FILES['input-b1']['name'] . "), we allow only (" . implode(",", $global['allowed']) . ")"; die(json_encode($obj)); } if (strcasecmp($extension, 'zip') == 0) { //$id = File::encodeAndsaveZipFile($_FILES['input-b1']['tmp_name'], $_FILES['input-b1']['name'], $key); $destination = "{$global['systemRootPath']}plugin/"; $obj->destination = $destination; - $path = $_FILES['input-b1']['tmp_name']; + $path = $_FILES['input-b1']['tmp_name']; $dir = "{$destination}/{$path_parts['filename']}"; if(is_dir($dir)){ exec("rm -R {$dir}"); } exec("unzip {$path} -d {$destination}"); } die(json_encode($obj)); diff --git a/objects/pluginRunUpdateScript.json.php b/objects/pluginRunUpdateScript.json.php index 72a714731..5f61320ab 100644 --- a/objects/pluginRunUpdateScript.json.php +++ b/objects/pluginRunUpdateScript.json.php @@ -1,23 +1,20 @@ loadFromUUID($_POST['uuid']); $obj->setName($_POST['name']); $obj->setDirName($_POST['dir']); if(empty($_POST['enable']) || $_POST['enable']==="false"){ $_POST['status'] = "inactive"; }else{ $_POST['status'] = "active"; } $obj->setStatus($_POST['status']); if(empty($obj->pluginversion)||is_null($obj->pluginversion)){ require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; - $p=AVideoPlugin::loadPlugin($_POST['dir']); + $p=AVideoPlugin::loadPlugin($_POST['dir']); $currentVersion=$p->getPluginVersion(); $obj->setPluginversion($currentVersion); Plugin::setCurrentVersionByUuid($_POST['uuid'], $currentVersion); - + } echo '{"status":"'.$obj->save().'"}'; diff --git a/objects/security.php b/objects/security.php index df7e6c8da..01f86f002 100644 --- a/objects/security.php +++ b/objects/security.php @@ -1,136 +1,135 @@ $value) { if (!empty($_GET[$value])) { if (!filter_var($_GET[$value], FILTER_VALIDATE_URL) || !preg_match("/^http.*/i", $_GET[$value])) { //_error_log($value.' attack ' . json_encode($_SERVER), AVideoLog::$SECURITY); unset($_GET[$value]); - }else{ + } else { $_GET[$value] = str_replace(array("'",'"',"<",">"), array("","","",""), $_GET[$value]); } } if (!empty($_POST[$value])) { if (!filter_var($_POST[$value], FILTER_VALIDATE_URL) || !preg_match("/^http.*/i", $_POST[$value])) { _error_log($value.' attack ' . json_encode($_SERVER), AVideoLog::$SECURITY); unset($_POST[$value]); - }else{ + } else { $_POST[$value] = str_replace(array("'",'"',"<",">"), array("","","",""), $_POST[$value]); } } } - if (!empty($_FILES)) { foreach ($_FILES as $key=>$value) { $_FILES[$key]['name'] = preg_replace('/[^a-z0-9.,()+& #-]/i', '', cleanString($_FILES[$key]['name'])); } } foreach ($securityRemoveNonChars as $value) { if (!empty($_POST[$value])) { if (is_string($_POST[$value])) { $_POST[$value] = str_replace('/[^a-z0-9./]/i', '', trim($_POST[$value])); - } else if (is_array($_POST[$value])) { + } elseif (is_array($_POST[$value])) { foreach ($_POST[$value] as $key => $value2) { if (is_string($_POST[$value][$key])) { $_POST[$value][$key] = str_replace('/[^a-z0-9./]/i', '', trim($_POST[$value][$key])); } } } } if (!empty($_GET[$value])) { if (is_string($_GET[$value])) { $_GET[$value] = str_replace('/[^a-z0-9./]/i', '', trim($_GET[$value])); - } else if (is_array($_GET[$value])) { + } elseif (is_array($_GET[$value])) { foreach ($_GET[$value] as $key => $value2) { if (is_string($_GET[$value][$key])) { $_GET[$value][$key] = str_replace('/[^a-z0-9./]/i', '', trim($_GET[$value][$key])); } } } } } foreach ($securityRemoveSingleQuotes as $value) { if (!empty($_POST[$value])) { if (is_string($_POST[$value])) { $_POST[$value] = str_replace("'", "", trim($_POST[$value])); - } else if (is_array($_POST[$value])) { + } elseif (is_array($_POST[$value])) { foreach ($_POST[$value] as $key => $value2) { if (is_string($_POST[$value][$key])) { $_POST[$value][$key] = str_replace("'", "", trim($_POST[$value][$key])); } } } } if (!empty($_GET[$value])) { if (is_string($_GET[$value])) { $_GET[$value] = str_replace("'", "", trim($_GET[$value])); - } else if (is_array($_GET[$value])) { + } elseif (is_array($_GET[$value])) { foreach ($_GET[$value] as $key => $value2) { if (is_string($_GET[$value][$key])) { $_GET[$value][$key] = str_replace("'", "", trim($_GET[$value][$key])); } } } } } foreach ($securityFilterInt as $value) { if (!empty($_POST[$value])) { - if(strtolower($_POST[$value])==="true"){ + if (strtolower($_POST[$value])==="true") { $_POST[$value] = 1; - }else{ + } else { $_POST[$value] = intval($_POST[$value]); } } if (!empty($_GET[$value])) { - if(strtolower($_GET[$value])==="true"){ + if (strtolower($_GET[$value])==="true") { $_GET[$value] = 1; - }else{ + } else { $_GET[$value] = intval($_GET[$value]); } } } foreach ($securityFilter as $value) { if (!empty($_POST[$value])) { $_POST[$value] = str_replace(array("'", '"', """, "'"), array('', '', '', ''), xss_esc($_POST[$value])); } if (!empty($_GET[$value])) { $_GET[$value] = str_replace(array("'", '"', """, "'"), array('', '', '', ''), xss_esc($_GET[$value])); } } if (!empty($_GET['sort']) && is_array($_GET['sort'])) { foreach ($_GET['sort'] as $key => $value) { $_GET['sort'][xss_esc($key)] = strcasecmp($value, "ASC") === 0 ? "ASC" : "DESC"; } } if (!empty($_POST['sort']) && is_array($_POST['sort'])) { foreach ($_POST['sort'] as $key => $value) { $_POST['sort'][xss_esc($key)] = strcasecmp($value, "ASC") === 0 ? "ASC" : "DESC"; } -} \ No newline at end of file +} diff --git a/objects/sendEmail.json.php b/objects/sendEmail.json.php index 157bc285e..faf925138 100644 --- a/objects/sendEmail.json.php +++ b/objects/sendEmail.json.php @@ -1,61 +1,61 @@ error = ""; if ($valid) { $msg = "Name: {$_POST['first_name']}
Email: {$_POST['email']}
Website: {$_POST['website']}

{$_POST['comment']}"; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/PHPMailer.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/SMTP.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/Exception.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/PHPMailer.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/SMTP.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/Exception.php'; //Create a new PHPMailer instance $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only //var_dump($mail->SMTPAuth, $mail); //Set who the message is to be sent from $replyTo = User::getEmail_(); if (empty($replyTo)) { $replyTo = $config->getContactEmail(); } $sendTo = $_POST['email']; // if it is from contact form send the message to the siteowner and the sender is the email on the form field if (!empty($_POST['contactForm'])) { $replyTo = $_POST['email']; $sendTo = $config->getContactEmail(); } if (filter_var($sendTo, FILTER_VALIDATE_EMAIL)) { $mail->AddReplyTo($replyTo); $mail->setFrom($replyTo); //Set who the message is to be sent to $mail->addAddress($sendTo); //Set the subject line $mail->Subject = 'Message From Site ' . $config->getWebSiteTitle() . " ({$_POST['first_name']})"; $mail->msgHTML($msg); //send the message, check for errors if (!$mail->send()) { $obj->error = __("Message could not be sent") . " (" . $mail->ErrorInfo.")"; } else { $obj->success = __("Message sent"); } } else { $obj->error = __("The email is invalid"); } } else { $obj->error = __("Your code is not valid"); } _error_log("sendEmail: ".$obj->error); header('Content-Type: application/json'); echo json_encode($obj); diff --git a/objects/sites.php b/objects/sites.php index 4a6f57cbf..7dcc9c974 100644 --- a/objects/sites.php +++ b/objects/sites.php @@ -1,77 +1,77 @@ name; } function getUrl() { return $this->url; } function getStatus() { return $this->status; } function setName($name) { $this->name = $name; } function setUrl($url) { $this->url = $url; } function setStatus($status) { $this->status = $status; } function getSecret() { return $this->secret; } function setSecret($secret) { $this->secret = $secret; } - + function save() { if(empty($this->getSecret())){ $this->setSecret(md5(uniqid())); } - + $siteURL = $this->getUrl(); if (substr($siteURL, -1) !== '/') { $siteURL .= "/"; } $this->setUrl($siteURL); return parent::save(); } static function getFromFileName($fileName){ $obj = new stdClass(); $obj->url = ""; $obj->secret = ""; $obj->filename = $fileName; $video = Video::getVideoFromFileNameLight($fileName); if(!empty($video['sites_id'])){ $site = new Sites($video['sites_id']); $obj->url = $site->getUrl(); $obj->secret = $site->getSecret(); } return $obj; } } diff --git a/objects/subscribe.php b/objects/subscribe.php index a50b2525e..5ece2b315 100644 --- a/objects/subscribe.php +++ b/objects/subscribe.php @@ -1,361 +1,361 @@ load($id); } if (!empty($subscriber_users_id)) { $this->email = $email; $this->users_id = $user_id; $this->subscriber_users_id = $subscriber_users_id; if (empty($this->id)) { $this->loadFromId($this->subscriber_users_id, $user_id, ""); } } } private function load($id) { $obj = self::getSubscribe($id); if (empty($obj)) return false; foreach ($obj as $key => $value) { $this->$key = $value; } return true; } private function loadFromEmail($email, $user_id, $status = "a") { $obj = self::getSubscribeFromEmail($email, $user_id, $status); if (empty($obj)) return false; foreach ($obj as $key => $value) { $this->$key = $value; } return true; } private function loadFromId($subscriber_users_id, $user_id, $status = "a") { $obj = self::getSubscribeFromID($subscriber_users_id, $user_id, $status); if (empty($obj)) return false; foreach ($obj as $key => $value) { $this->$key = $value; } return true; } function save() { global $global; if (!empty($this->id)) { $sql = "UPDATE subscribes SET status = '{$this->status}', notify = '{$this->notify}',ip = '" . getRealIpAddr() . "', modified = now() WHERE id = {$this->id}"; } else { $sql = "INSERT INTO subscribes ( users_id, email,status,ip, created, modified, subscriber_users_id) VALUES ('{$this->users_id}','{$this->email}', 'a', '" . getRealIpAddr() . "',now(), now(), '$this->subscriber_users_id')"; } return sqlDAL::writeSql($sql); } static function getSubscribe($id) { global $global; $id = intval($id); $sql = "SELECT * FROM subscribes WHERE id = $id LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { $subscribe = $data; } else { $subscribe = false; } return $subscribe; } static function getSubscribeFromEmail($email, $user_id, $status = "a") { global $global; $status = str_replace("'","", $status); $sql = "SELECT * FROM subscribes WHERE email = '$email' AND users_id = {$user_id} "; if (!empty($status)) { $sql .= " AND status = '{$status}' "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { $subscribe = $data; } else { $subscribe = false; } return $subscribe; } static function getSubscribeFromID($subscriber_users_id, $user_id, $status = "a") { global $global; $status = str_replace("'","", $status); $sql = "SELECT * FROM subscribes WHERE subscriber_users_id = '$subscriber_users_id' AND users_id = {$user_id} "; if (!empty($status)) { $sql .= " AND status = '{$status}' "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { $subscribe = $data; } else { $subscribe = false; } return $subscribe; } - + static function isSubscribed($subscribed_to_user_id, $user_id=0) { if(empty($user_id)){ if(User::isLogged()){ $user_id = User::getId(); }else{ return false; } } $s = self::getSubscribeFromID($subscribed_to_user_id, $user_id); return !empty($s['users_id']); } /** * return all subscribers that has subscribe to an user channel * @global type $global * @param type $user_id * @return boolean */ static function getAllSubscribes($user_id = "", $status = "a") { global $global; $cacheName = "getAllSubscribes_{$user_id}_{$status}_". getCurrentPage()."_". getRowCount(); $subscribe = ObjectYPT::getCache($cacheName, 300);// 5 minutes if(empty($subscribe)){ $status = str_replace("'","", $status); $sql = "SELECT subscriber_users_id as subscriber_id, s.id, s.status, s.ip, s.users_id, s.notify, " . " s.subscriber_users_id , s.created , s.modified, suId.email as email, suId.emailVerified as emailVerified FROM subscribes as s " //. " LEFT JOIN users as su ON s.email = su.email " . " LEFT JOIN users as suId ON suId.id = s.subscriber_users_id " . " LEFT JOIN users as u ON users_id = u.id WHERE 1=1 AND subscriber_users_id > 0 "; if (!empty($user_id)) { $sql .= " AND users_id = {$user_id} "; } if (!empty($status)) { $sql .= " AND u.status = '{$status}' "; $sql .= " AND suId.status = '{$status}' "; //$sql .= " AND su.status = '{$status}' "; } //$sql .= " GROUP BY subscriber_id "; $sql .= BootGrid::getSqlFromPost(array('email')); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $subscribe = array(); if ($res != false) { $emails = array(); foreach ($fullData as $row) { if (in_array($row['email'], $emails)) { //continue; } $emails[] = $row['email']; $row['identification'] = User::getNameIdentificationById($row['subscriber_id']); if ($row['identification'] === __("Unknown User")) { $row['identification'] = $row['email']; } $row['backgroundURL'] = User::getBackground($row['subscriber_id']); $row['photoURL'] = User::getPhoto($row['subscriber_id']); $subscribe[] = $row; } //$subscribe = $res->fetch_all(MYSQLI_ASSOC); } else { $subscribe = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } ObjectYPT::setCache($cacheName, $subscribe); }else{ $subscribe = object_to_array($subscribe); } return $subscribe; } /** * return all channels that a user has subscribed * @global type $global * @param type $user_id * @return boolean */ static function getSubscribedChannels($user_id) { global $global; $sql = "SELECT s.* FROM subscribes as s WHERE status = 'a' AND subscriber_users_id = ? "; $res = sqlDAL::readSql($sql, "i", array($user_id)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $subscribe = array(); if ($res != false) { foreach ($fullData as $row) { if($row['users_id']==$user_id){ continue; } $row['identification'] = User::getNameIdentificationById($row['users_id']); if ($row['identification'] === __("Unknown User")) { $row['identification'] = $row['email']; } $row['backgroundURL'] = User::getBackground($row['users_id']); $row['photoURL'] = User::getPhoto($row['users_id']); $subscribe[] = $row; } //$subscribe = $res->fetch_all(MYSQLI_ASSOC); } else { $subscribe = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $subscribe; } static function getTotalSubscribes($user_id = "") { global $global; $sql = "SELECT id FROM subscribes WHERE status = 'a' AND subscriber_users_id > 0 "; if (!empty($user_id)) { $sql .= " AND users_id = '{$user_id}' "; } $sql .= BootGrid::getSqlSearchFromPost(array('email')); $res = sqlDAL::readSql($sql); $numRows = sqlDAL::num_rows($res); sqlDAL::close($res); return $numRows; } function toggle() { if (empty($this->status) || $this->status == "i") { $this->status = 'a'; } else { $this->status = 'i'; } $this->save(); } function notifyToggle() { if (empty($this->notify)) { $this->notify = 1; } else { $this->notify = 0; } $this->save(); } function getStatus() { return $this->status; } function getNotify() { return $this->notify; } function setNotify($notify) { $this->notify = $notify; } static function getButton($user_id) { global $global, $advancedCustom; - + if(!empty($advancedCustom->removeSubscribeButton)){ return ""; } - + $total = static::getTotalSubscribes($user_id); $subscribe = "
" . "" . "" . "
"; //show subscribe button with mail field $popover = ""; $script = ""; if (User::isLogged()) { //check if the email is logged $email = User::getMail(); $subs = Subscribe::getSubscribeFromID(User::getId(), $user_id); $popover = ""; // show unsubscribe Button $subscribe = "
"; if(!empty($subs) && $subs['status']==='a'){ $subscribe .= ""; $subscribe .= ""; }else{ $subscribe .= ""; $subscribe .= ""; } $subscribe .= "
"; if (!empty($subs['notify'])) { $notify = ''; $notNotify = 'hidden'; } else { $notify = 'hidden'; $notNotify = ''; } - $subscribe .= ''; $script = ""; } - + return $subscribe . $popover . $script; } function getSubscriber_users_id() { return $this->subscriber_users_id; } function setSubscriber_users_id($subscriber_users_id) { $this->subscriber_users_id = $subscriber_users_id; } } diff --git a/objects/uploadChannelArt.php b/objects/uploadChannelArt.php index 77fff6329..01cf669ed 100644 --- a/objects/uploadChannelArt.php +++ b/objects/uploadChannelArt.php @@ -1,48 +1,48 @@ error = true; if (!User::isLogged()) { $obj->msg = 'You cant edit this file'; die(json_encode($obj)); } header('Content-Type: application/json'); // A list of permitted file extensions $allowed = array('jpg', 'jpeg', 'gif', 'png'); if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; die(json_encode($obj)); } - + $tmpDestination = "{$global['systemRootPath']}videos/userPhoto/tmp_background".User::getId().".". $extension; $obj->file = "videos/userPhoto/background".User::getId().".jpg"; $oldfile = "{$global['systemRootPath']}videos/userPhoto/background".User::getId().".png"; - + if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $tmpDestination)) { $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . "{$global['systemRootPath']}videos/" . $filename . $ext; die(json_encode($obj)); } convertImage($tmpDestination, $global['systemRootPath'].$obj->file, 70); unlink($tmpDestination); if(file_exists($oldfile)){ unlink($oldfile); } - + echo "{}"; exit; } $obj->msg = "\$_FILES Error"; $obj->FILES = $_FILES; die(json_encode($obj)); diff --git a/objects/user.php b/objects/user.php index 15d343813..86eab0a0e 100644 --- a/objects/user.php +++ b/objects/user.php @@ -1,2265 +1,2265 @@ user = $user; if ($password !== false) { $this->password = $password; } else { $this->loadFromUser($user); } } else { // get data from id $this->load($id); } } function getEmail() { return $this->email; } function getUser() { return $this->user; } function getAbout() { return str_replace(array('\\\\\\\n'), array("\n"), $this->about); } function setAbout($about) { $this->about = xss_esc($about); } function getPassword() { return $this->password; } function getCanStream() { return $this->canStream; } function setCanStream($canStream) { $this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1; } function getCanViewChart() { return $this->canViewChart; } function setCanViewChart($canViewChart) { $this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1; } function getCanCreateMeet() { return $this->canCreateMeet; } function setCanCreateMeet($canCreateMeet) { $this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1; ; } function getCanUpload() { return $this->canUpload; } function setCanUpload($canUpload) { $this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1; } function getAnalyticsCode() { return $this->analyticsCode; } function setAnalyticsCode($analyticsCode) { preg_match("/(ua-\d{4,9}-\d{1,4})/i", $analyticsCode, $matches); if (!empty($matches[1])) { $this->analyticsCode = $matches[1]; } else { $this->analyticsCode = ""; } } function getAnalytics() { $id = $this->getId(); $aCode = $this->getAnalyticsCode(); if (!empty($id) && !empty($aCode)) { $code = " "; } else { $code = ""; } return $code; } function addExternalOptions($id, $value) { $eo = unserialize(base64_decode($this->externalOptions)); if (!is_array($eo)) { $eo = array(); } $eo[$id] = $value; $this->setExternalOptions($eo); return $this->save(); } function removeExternalOptions($id) { $eo = unserialize(base64_decode($this->externalOptions)); unset($eo[$id]); $this->setExternalOptions($eo); return $this->save(); } function setExternalOptions($options) { //we convert it to base64 to sanitize the input since we do not validate input from externalOptions $this->externalOptions = base64_encode(serialize($options)); } function getExternalOption($id) { $eo = unserialize(base64_decode($this->externalOptions)); if (empty($eo[$id])) { return NULL; } return $eo[$id]; } private function load($id) { $id = intval($id); if (empty($id)) { return false; } $user = self::getUserDb($id); if (empty($user)) return false; foreach ($user as $key => $value) { $this->$key = $value; } return true; } private function loadFromUser($user) { $userLoaded = self::getUserDbFromUser($user); if (empty($userLoaded)) { return false; } _error_log("User::loadFromUser($user) "); _error_log("User::loadFromUser json " . json_encode(debug_backtrace())); foreach ($userLoaded as $key => $value) { $this->$key = $value; } return true; } function loadSelfUser() { $this->load($this->getId()); } static function getId() { if (self::isLogged()) { return $_SESSION['user']['id']; } else { return false; } } static function getEmail_() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } function getBdId() { return $this->id; } static function updateSessionInfo() { if (self::isLogged()) { $user = self::getUserDb($_SESSION['user']['id']); $_SESSION['user'] = $user; } } static function getName() { if (self::isLogged()) { return $_SESSION['user']['name']; } else { return false; } } static function getUserName() { if (self::isLogged()) { return $_SESSION['user']['user']; } else { return false; } } static function getUserChannelName() { if (self::isLogged()) { if (empty($_SESSION['user']['channelName'])) { $_SESSION['user']['channelName'] = self::_recommendChannelName(); $user = new User(User::getId()); $user->setChannelName($_SESSION['user']['channelName']); $user->save(); } return $_SESSION['user']['channelName']; } else { return false; } } static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0) { if (empty($users_id)) { if (!empty(User::getId())) { $users_id = User::getId(); } } if (empty($users_id)) { $newChannelName = $name . "_" . uniqid(); if (strlen($newChannelName) > 40) { $newChannelName = uniqid(); } return $newChannelName; } if ($try > 10) { _error_log("User:_recommendChannelName too many tries ({$name}) (" . User::getId() . ") ", AVideoLog::$ERROR); return uniqid(); } if (empty($name)) { $name = self::getNameIdentification(); if ($name == __("Unknown User") && !empty($unknown)) { $name = $unknown; } $name = cleanString($name); } // in case is a email get only the username $parts = explode("@", $name); $name = $parts[0]; // do not exceed 36 chars to leave some room for the unique id; $name = substr($name, 0, 36); if (!Permissions::canAdminUsers()) { $user = self::getUserFromChannelName($name); if ($user && $user['id'] !== $users_id) { return self::_recommendChannelName($name . "_" . uniqid(), $try + 1); } } return $name; } static function getUserFromChannelName($channelName) { $channelName = cleanString($channelName); global $global; $channelName = $global['mysqli']->real_escape_string($channelName); $sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($channelName)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } else { return false; } } /** * return an name to identify the user * @return String */ static function getNameIdentification() { global $advancedCustomUser; if (self::isLogged()) { if (!empty(self::getName()) && empty($advancedCustomUser->doNotIndentifyByName)) { return self::getName(); } if (!empty(self::getMail()) && empty($advancedCustomUser->doNotIndentifyByEmail)) { return self::getMail(); } if (!empty(self::getUserName()) && empty($advancedCustomUser->doNotIndentifyByUserName)) { return self::getUserName(); } if (!empty(self::getUserChannelName())) { return self::getUserChannelName(); } } return __("Unknown User"); } /** * return an name to identify the user from database * @return String */ function getNameIdentificationBd() { global $advancedCustomUser; if (!empty($this->name) && empty($advancedCustomUser->doNotIndentifyByName)) { return $this->name; } if (!empty($this->email) && empty($advancedCustomUser->doNotIndentifyByEmail)) { return $this->email; } if (!empty($this->user) && empty($advancedCustomUser->doNotIndentifyByUserName)) { return $this->user; } if (!empty($this->channelName)) { return $this->channelName; } return __("Unknown User"); } static function getNameIdentificationById($id = "") { if (!empty($id)) { $user = new User($id); return $user->getNameIdentificationBd(); } return __("Unknown User"); } static function getUserPass() { if (self::isLogged()) { return $_SESSION['user']['password']; } else { return false; } } function _getName() { return $this->name; } static function _getPhoto($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['photoURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['photoURL']; } if (!empty($photo)) { if (preg_match("/videos\/userPhoto\/.*/", $photo) && file_exists($global['systemRootPath'] . $photo)) { return $photo; } else { $photoPath = "/videos/userPhoto/photo{$id}.png"; $content = url_get_contents($photo); file_put_contents($global['systemRootPath'] . $photoPath, $content); $photo = $photoPath; } } if (empty($photo)) { $photo = "view/img/userSilhouette.jpg"; } return $photo; } static function getPhoto($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['photoURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['photoURL']; } if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) { if (file_exists($global['systemRootPath'] . $photo)) { $photo = $global['webSiteRootURL'] . $photo . "?" . filemtime($global['systemRootPath'] . $photo); } else { $photo = ""; } } if (empty($photo)) { $photo = $global['webSiteRootURL'] . "view/img/userSilhouette.jpg"; } return $photo; } static function _getOGImage($users_id) { return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg"; } static function deleteOGImage($users_id) { global $global; $photo = $global['systemRootPath'] . self::_getOGImage($users_id); @unlink($photo); } static function getOGImage($users_id = "") { global $global; $photo = self::_getPhoto($users_id); if ($photo == "view/img/userSilhouette.jpg") { return "{$global['webSiteRootURL']}view/img/userSilhouette.jpg"; } if (empty($photo)) { return false; } $source = $global['systemRootPath'] . $photo; $destination = $global['systemRootPath'] . self::_getOGImage($users_id); convertImageToOG($source, $destination); return $global['webSiteRootURL'] . self::_getOGImage($users_id); ; } static function getEmailVerifiedIcon($id = "") { global $advancedCustomUser; $mark = ""; if (!empty($advancedCustomUser->showEmailVerifiedMark)) { if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $verified = $user['emailVerified']; } } elseif (self::isLogged()) { $verified = $_SESSION['user']['emailVerified']; } if (!empty($verified)) { $mark .= ' '; } else { //return ''; $mark .= ''; } } if ($advancedCustomUser->Checkmark1Enabled) { if (User::externalOptionsFromUserID($id, "checkmark1")) { $mark .= " " . $advancedCustomUser->Checkmark1HTML; } } if ($advancedCustomUser->Checkmark2Enabled) { if (User::externalOptionsFromUserID($id, "checkmark2")) { $mark .= " " . $advancedCustomUser->Checkmark2HTML; } } if ($advancedCustomUser->Checkmark3Enabled) { if (User::externalOptionsFromUserID($id, "checkmark3")) { $mark .= " " . $advancedCustomUser->Checkmark3HTML; } } return $mark; } function getPhotoDB() { global $global; $photo = self::getPhoto($this->id); return $photo; } static function getBackground($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['backgroundURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['backgroundURL']; } if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) { if (file_exists($global['systemRootPath'] . $photo)) { $photo = $global['webSiteRootURL'] . $photo; } else { $photo = ""; } } if (empty($photo)) { $photo = $global['webSiteRootURL'] . "view/img/background.png"; } return $photo; } static function getMail() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } function save($updateUserGroups = false) { global $global, $config, $advancedCustom, $advancedCustomUser; if (is_object($config) && $config->currentVersionLowerThen('5.6')) { // they dont have analytics code return false; } if (empty($this->user) || empty($this->password)) { //echo "u:" . $this->user . "|p:" . strlen($this->password); _error_log('Error : ' . __("You need a user and passsword to register")); return false; } if (empty($this->isAdmin)) { $this->isAdmin = "false"; } if (empty($this->canStream)) { if (empty($this->id)) { // it is a new user if (empty($advancedCustomUser->newUsersCanStream)) { $this->canStream = "0"; } else { $this->canStream = "1"; } } else { $this->canStream = "0"; } } if (empty($this->canUpload)) { $this->canUpload = "0"; } if (empty($this->status)) { $this->status = 'a'; } if (empty($this->emailVerified)) $this->emailVerified = "false"; $this->user = $global['mysqli']->real_escape_string($this->user); $this->password = $global['mysqli']->real_escape_string($this->password); $this->name = $global['mysqli']->real_escape_string($this->name); $this->status = $global['mysqli']->real_escape_string($this->status); $this->about = $global['mysqli']->real_escape_string($this->about); $this->about = preg_replace("/(\\\)+n/", "\n", $this->about); $this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id); $this->channelName = $global['mysqli']->real_escape_string($this->channelName); if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === FALSE) { $this->donationLink = ""; } if (!empty($this->id)) { $formats = "ssssiiii"; $values = array($this->user, $this->password, $this->email, $this->name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet); $sql = "UPDATE users SET user = ?, password = ?, " . "email = ?, name = ?, isAdmin = ?," . "canStream = ?,canUpload = ?,canCreateMeet = ?,"; if (isset($this->canViewChart)) { $formats .= "i"; $values[] = $this->canViewChart; $sql .= "canViewChart = ?, "; } $formats .= "ssssssissssssssssi"; $values[] = $this->status; $values[] = $this->photoURL; $values[] = $this->backgroundURL; $values[] = $this->recoverPass; $values[] = $this->about; $values[] = $this->channelName; $values[] = $this->emailVerified; $values[] = $this->analyticsCode; $values[] = $this->externalOptions; $values[] = $this->first_name; $values[] = $this->last_name; $values[] = $this->address; $values[] = $this->zip_code; $values[] = $this->country; $values[] = $this->region; $values[] = $this->city; $values[] = $this->donationLink; $values[] = $this->id; $sql .= "status = ?, " . "photoURL = ?, backgroundURL = ?, " . "recoverPass = ?, about = ?, " . " channelName = ?, emailVerified = ? , analyticsCode = ?, externalOptions = ? , " . " first_name = ? , last_name = ? , address = ? , zip_code = ? , country = ? , region = ? , city = ? , donationLink = ? , " . " modified = now() WHERE id = ?"; } else { $formats = "ssssiiiissssss"; $values = array($this->user, $this->password, $this->email, $this->name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet, $this->status, $this->photoURL, $this->recoverPass, $this->channelName, $this->analyticsCode, $this->externalOptions); $sql = "INSERT INTO users (user, password, email, name, isAdmin, canStream, canUpload, canCreateMeet, canViewChart, status,photoURL,recoverPass, created, modified, channelName, analyticsCode, externalOptions) " . " VALUES (?,?,?,?,?,?,?,?, false, " . "?,?,?, now(), now(),?,?,?)"; } $insert_row = sqlDAL::writeSql($sql, $formats, $values); if ($insert_row) { if (empty($this->id)) { $id = $global['mysqli']->insert_id; if (!empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { self::sendVerificationLink($id); } } else { $id = $this->id; } if ($updateUserGroups) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; // update the user groups UserGroups::updateUserGroups($id, $this->userGroups); } return $id; } else { _error_log(' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); return false; } } static function getChannelOwner($channelName) { global $global; $channelName = $global['mysqli']->real_escape_string($channelName); $sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($channelName)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $user = $result; } else { $user = false; } return $user; } static function getFromUsername($user) { global $global; $user = $global['mysqli']->real_escape_string($user); $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $user = $result; } else { $user = false; } return $user; } private static function setCacheWatchVideo($cacheName, $value) { if (!User::isLogged()) { ObjectYPT::setCache($cacheName, $value); ; } else { ObjectYPT::setSessionCache($cacheName, $value); } } static function canWatchVideo($videos_id) { $cacheName = "canWatchVideo$videos_id"; if (!User::isLogged()) { $cache = ObjectYPT::getCache($cacheName, 3600); } else { $cache = ObjectYPT::getSessionCache($cacheName, 600); } if (isset($cache)) { return $cache; } if (empty($videos_id)) { _error_log("User::canWatchVideo Video is empty ({$videos_id})"); return false; } if (User::isAdmin()) { return true; } $video = new Video("", "", $videos_id); if ($video->getStatus() === 'i') { _error_log("User::canWatchVideo Video is inactive ({$videos_id})"); self::setCacheWatchVideo($cacheName, false); return false; } $user = new User($video->getUsers_id()); if ($user->getStatus() === 'i') { _error_log("User::canWatchVideo User is inactive ({$videos_id})"); self::setCacheWatchVideo($cacheName, false); return false; } if (AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) { self::setCacheWatchVideo($cacheName, true); return true; } // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { // check if any plugin restrict access to this video if (!AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) { if (User::isLogged()) { _error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [" . User::getId() . "] can not see ({$videos_id})"); } else { _error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [not logged] can not see ({$videos_id})"); } self::setCacheWatchVideo($cacheName, false); return false; } else { self::setCacheWatchVideo($cacheName, true); return true; // the video is public } } if (!User::isLogged()) { _error_log("User::canWatchVideo You are not logged so can not see ({$videos_id}) session_id=" . session_id() . " SCRIPT_NAME=" . $_SERVER["SCRIPT_NAME"] . " IP = " . getRealIpAddr()); self::setCacheWatchVideo($cacheName, false); return false; } // if is not public check if the user is on one of its groups $rowsUser = UserGroups::getUserGroups(User::getId()); foreach ($rows as $value) { foreach ($rowsUser as $value2) { if ($value['id'] === $value2['id']) { self::setCacheWatchVideo($cacheName, true); return true; } } } _error_log("User::canWatchVideo The user " . User::getId() . " is not on any of the user groups ({$videos_id}) " . json_encode($rows)); self::setCacheWatchVideo($cacheName, false); ; return false; } static function canWatchVideoWithAds($videos_id) { if (empty($videos_id)) { _error_log("User::canWatchVideo (videos_id is empty) " . $videos_id); return false; } if (User::isAdmin()) { return true; } if (AVideoPlugin::userCanWatchVideoWithAds(User::getId(), $videos_id)) { return true; } _error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id); if (self::canWatchVideo($videos_id)) { return true; } _error_log("User::canWatchVideo (No can not) " . $videos_id); return false; } function delete() { if (!self::isAdmin()) { return false; } // cannot delete yourself if (self::getId() === $this->id) { return false; } global $global; if (!empty($this->id)) { $sql = "DELETE FROM users WHERE id = ?"; } else { return false; } return sqlDAL::writeSql($sql, "i", array($this->id)); } const USER_LOGGED = 0; const USER_NOT_VERIFIED = 1; const USER_NOT_FOUND = 2; const CAPTCHA_ERROR = 3; const REQUIRE2FA = 4; function login($noPass = false, $encodedPass = false) { if (User::isLogged()) { return false; } global $global, $advancedCustom, $advancedCustomUser, $config; if (strtolower($encodedPass) === 'false') { $encodedPass = false; } //_error_log("user::login: noPass = $noPass, encodedPass = $encodedPass, this->user, $this->user " . getRealIpAddr()); if ($noPass) { $user = $this->find($this->user, false, true); } else { $user = $this->find($this->user, $this->password, true, $encodedPass); } if (!self::checkLoginAttempts()) { return self::CAPTCHA_ERROR; } if (session_status() == PHP_SESSION_NONE) { session_start(); } // check for multiple logins attempts to prevent hacking end // if user is not verified if (!empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { unset($_SESSION['user']); self::sendVerificationLink($user['id']); return self::USER_NOT_VERIFIED; } else if ($user) { $_SESSION['user'] = $user; $this->setLastLogin($_SESSION['user']['id']); $rememberme = 0; if ((!empty($_POST['rememberme']) && $_POST['rememberme'] == "true") || !empty($_COOKIE['rememberme'])) { $expires = strtotime("+ 1 year"); $rememberme = 1; } else { $expires = 0; } _setcookie("rememberme", $rememberme, $expires); _setcookie("user", $user['user'], $expires); _setcookie("pass", $user['password'], $expires); AVideoPlugin::onUserSignIn($_SESSION['user']['id']); $_SESSION['loginAttempts'] = 0; session_write_close(); return self::USER_LOGGED; } else { unset($_SESSION['user']); return self::USER_NOT_FOUND; } } static function isCaptchaNeed() { global $advancedCustomUser; // check for multiple logins attempts to prevent hacking if (!empty($_SESSION['loginAttempts']) && !empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) { if (isMobile()) { $advancedCustomUser->requestCaptchaAfterLoginsAttempts += 10; } if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) { return true; } } return false; } static function checkLoginAttempts() { global $advancedCustomUser, $global; // check for multiple logins attempts to prevent hacking if (empty($_SESSION['loginAttempts'])) { _session_start(); $_SESSION['loginAttempts'] = 0; } if (!empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) { _session_start(); $_SESSION['loginAttempts']++; if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) { if (empty($_POST['captcha'])) { return false; } require_once $global['systemRootPath'] . 'objects/captcha.php'; if (!Captcha::validation($_POST['captcha'])) { return false; } } } return true; } static function getCaptchaFormIfNeed() { // check for multiple logins attempts to prevent hacking if (self::isCaptchaNeed()) { return self::getCaptchaForm(); } return ""; } static function getCaptchaForm($uid = "") { global $global; return '
' . '
'; } private function setLastLogin($user_id) { global $global; if (empty($user_id)) { die('Error : setLastLogin '); } $sql = "UPDATE users SET lastLogin = now(), modified = now() WHERE id = ?"; return sqlDAL::writeSql($sql, "i", array($user_id)); } static function logoff() { global $global, $justLogoff; $justLogoff = true; _session_start(); ObjectYPT::deleteAllSessionCache(); _unsetcookie('rememberme'); _unsetcookie('user'); _unsetcookie('pass'); unset($_SESSION['user']); } static private function recreateLoginFromCookie() { global $justLogoff, $justTryToRecreateLoginFromCookie; if (empty($justTryToRecreateLoginFromCookie) && empty($justLogoff) && empty($_SESSION['user']['id'])) { $justTryToRecreateLoginFromCookie = 1; if ((!empty($_COOKIE['user'])) && (!empty($_COOKIE['pass'])) && (!empty($_COOKIE['rememberme']))) { $user = new User(0, $_COOKIE['user'], false); $user->setPassword($_COOKIE['pass'], true); // $dbuser = self::getUserDbFromUser($_COOKIE['user']); $resp = $user->login(false, true); _error_log("user::recreateLoginFromCookie: do cookie-login: " . $_COOKIE['user'] . " result: " . $resp); if (0 == $resp) { _error_log("success " . $_SESSION['user']['id']); } else { _error_log("user::recreateLoginFromCookie: do logoff: " . $_COOKIE['user'] . " result: " . $resp); self::logoff(); } } } } static function isLogged() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['id']); } static function isVerified() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['emailVerified']); } static function isAdmin() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']); } static function canStream() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']) || !empty($_SESSION['user']['canStream']); } static function externalOptions($id) { if (!empty($_SESSION['user']['externalOptions'])) { $externalOptions = unserialize(base64_decode($_SESSION['user']['externalOptions'])); if (isset($externalOptions[$id])) { if ($externalOptions[$id] == "true") $externalOptions[$id] = true; else if ($externalOptions[$id] == "false") $externalOptions[$id] = false; return $externalOptions[$id]; } } return false; } static function externalOptionsFromUserID($users_id, $id) { $user = self::findById($users_id); if ($user) { if (!is_null($user['externalOptions'])) { $externalOptions = unserialize(base64_decode($user['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($id != $k) { continue; } if ($v == "true") $v = 1; else if ($v == "false") $v = 0; return $v; } } } } return false; } function thisUserCanStream() { if ($this->status === 'i') { return false; } return !empty($this->isAdmin) || !empty($this->canStream); } private function find($user, $pass, $mustBeactive = false, $encodedPass = false) { global $global, $advancedCustom; $formats = ""; $values = array(); $user = $global['mysqli']->real_escape_string($user); $sql = "SELECT * FROM users WHERE user = ? "; $formats .= "s"; $values[] = $user; if ($mustBeactive) { $sql .= " AND status = 'a' "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, $formats, $values, true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { if ($pass !== false) { if (!encryptPasswordVerify($pass, $result['password'], $encodedPass)) { if (!empty($advancedCustom) && $advancedCustom->enableOldPassHashCheck) { _error_log("Password check new hash pass does not match, trying MD5"); return $this->find_Old($user, $pass, $mustBeactive, $encodedPass); } else { return false; } } } $user = $result; } else { _error_log("Password check new hash user not found"); //check if is the old password style $user = false; //$user = false; } return $user; } /** * this is the deprecated function, with week password * @global type $global * @param type $user * @param type $pass * @param type $mustBeactive * @param type $encodedPass * @return boolean */ private function find_Old($user, $pass, $mustBeactive = false, $encodedPass = false) { global $global; $formats = ""; $values = array(); $user = $global['mysqli']->real_escape_string($user); $sql = "SELECT * FROM users WHERE user = ? "; $formats .= "s"; $values[] = $user; if ($mustBeactive) { $sql .= " AND status = 'a' "; } if ($pass !== false) { if (!$encodedPass || $encodedPass === 'false') { _error_log("Password check Old not encoded pass"); $passEncoded = md5($pass); } else { _error_log("Password check Old encoded pass"); $passEncoded = $pass; } $sql .= " AND password = ? "; $formats .= "s"; $values[] = $passEncoded; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, $formats, $values, true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { if (!$encodedPass || $encodedPass === 'false') { //update the password $u = new User($result['id']); $u->setPassword($pass); $u->save(); $result['password'] = $u->getPassword(); } $user = $result; } else { $user = false; } if (empty($user)) { _error_log("Password check Old not found"); } else { _error_log("Password check Old found"); } return $user; } static private function findById($id) { global $global; $id = intval($id); if (empty($id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $user = $result; } else { $user = false; } return $user; } static function findByEmail($email) { global $global; $email = trim($email); if (empty($email)) { return false; } $sql = "SELECT * FROM users WHERE email = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($email)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { $user = $result; } else { $user = false; } return $user; } static private function getUserDb($id) { global $global; $id = intval($id); if (empty($id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1;"; $res = sqlDAL::readSql($sql, "i", array($id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } static private function getUserDbFromUser($user) { global $global; if (empty($user)) { return false; } $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } static function getUserFromID($users_id) { global $global; if (empty($users_id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($users_id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { $user['groups'] = UserGroups::getUserGroups($user['id']); $user['identification'] = self::getNameIdentificationById($user['id']); $user['photo'] = self::getPhoto($user['id']); $user['background'] = self::getBackground($user['id']); $user['tags'] = self::getTags($user['id']); $user['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $user['name']); $user['isEmailVerified'] = $user['emailVerified']; if (!is_null($user['externalOptions'])) { $externalOptions = unserialize(base64_decode($user['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($v == "true") $v = 1; else if ($v == "false") $v = 0; $user[$k] = $v; } } } unset($user['password']); unset($user['recoverPass']); if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) { unset($user['first_name']); unset($user['last_name']); unset($user['address']); unset($user['zip_code']); unset($user['country']); unset($user['region']); unset($user['city']); } $user = $user; return $user; } return false; } static function getUserFromEmail($email) { $sql = "SELECT * FROM users WHERE email = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($email)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } function setUser($user) { global $advancedCustomUser; if (empty($advancedCustomUser->userCanChangeUsername)) { if (!empty($this->user)) { return false; } } $this->user = strip_tags($user); } function setName($name) { $this->name = strip_tags($name); } function setEmail($email) { global $advancedCustomUser; $email = strip_tags($email); if (!empty($advancedCustomUser->emailMustBeUnique)) { if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } $userFromEmail = User::getUserFromEmail($email); if (!empty($userFromEmail)) { return false; } } $this->email = $email; return true; } function setPassword($password, $doNotEncrypt = false) { if (!empty($password)) { if ($doNotEncrypt) { $this->password = ($password); } else { $this->password = encryptPassword($password); } } } function setIsAdmin($isAdmin) { if (empty($isAdmin) || $isAdmin === "false" || !User::isAdmin()) { $isAdmin = "0"; } else { $isAdmin = "1"; } $this->isAdmin = $isAdmin; } function setStatus($status) { $this->status = strip_tags($status); } function getPhotoURL() { return $this->photoURL; } function setPhotoURL($photoURL) { $this->photoURL = strip_tags($photoURL); } static function getAllUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } $users_groups_id = intval($users_groups_id); if(empty($users_groups_id)){ return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users u WHERE 1=1 "; $sql .= " AND id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlFromPost($searchFields); $user = array(); require_once $global['systemRootPath'] . 'objects/userGroups.php'; $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } static function getTotalUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } $users_groups_id = intval($users_groups_id); if(empty($users_groups_id)){ return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT id FROM users WHERE 1=1 "; $sql .= " AND id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user')); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); return $result; } static function getAllUsers($ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users WHERE 1=1 "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlFromPost($searchFields); $user = array(); require_once $global['systemRootPath'] . 'objects/userGroups.php'; $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } static private function getUserInfoFromRow($row) { $row['groups'] = UserGroups::getUserGroups($row['id']); $row['identification'] = self::getNameIdentificationById($row['id']); $row['photo'] = self::getPhoto($row['id']); $row['background'] = self::getBackground($row['id']); $row['tags'] = self::getTags($row['id']); $row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']); $row['isEmailVerified'] = $row['emailVerified']; if (!is_null($row['externalOptions'])) { $externalOptions = unserialize(base64_decode($row['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($v == "true") $v = 1; else if ($v == "false") $v = 0; $row[$k] = $v; } } } unset($row['password']); unset($row['recoverPass']); if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) { unset($row['first_name']); unset($row['last_name']); unset($row['address']); unset($row['zip_code']); unset($row['country']); unset($row['region']); unset($row['city']); } return $row; } static function getAllUsersThatHasVideos($ignoreAdmin = false) { if (!self::isAdmin() && !$ignoreAdmin) { return false; } global $global; $sql = "SELECT * FROM users u WHERE status = 'a' AND (canUpload = 1 || isAdmin = 1) AND " . " (SELECT count(id) FROM videos where users_id = u.id )>0 "; $user = array(); $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } static function getTotalUsers($ignoreAdmin = false, $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT id FROM users WHERE 1=1 "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user')); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); return $result; } static function userExists($user) { global $global; $user = $global['mysqli']->real_escape_string($user); $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user['id']; } else { return false; } } static function idExists($users_id) { global $global; $users_id = intval($users_id); $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($users_id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user['id']; } else { return false; } } static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false) { global $global, $advancedCustomUser; $user = $global['mysqli']->real_escape_string($user); $userId = 0; if (!$userId = self::userExists($user)) { if (empty($pass)) { $pass = uniqid(); } $pass = encryptPassword($pass); $userObject = new User(0, $user, $pass); $userObject->setEmail($email); $userObject->setName($name); $userObject->setIsAdmin($isAdmin); $userObject->setPhotoURL($photoURL); $userObject->setEmailVerified($emailVerified); $userId = $userObject->save(); if (!empty($userId)) { if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup UserGroups::updateUserGroups($userId, array($advancedCustomUser->userDefaultUserGroup->value), true); } } return $userId; } else { if ($emailVerified) { $userObj = new User($userId); if (!$userObj->getEmailVerified()) { $userObj->setEmailVerified(1); $userObj->save(); } } } return $userId; } function getRecoverPass() { return $this->recoverPass; } function setRecoverPass($recoverPass, $forceChange = false) { // let the same recover pass if it was 10 minutes ago if (empty($forceChange) && !empty($this->recoverPass) && !empty($recoverPass) && !empty($this->modified) && strtotime($this->modified) > strtotime("-10 minutes")) { return $this->recoverPass; } $this->recoverPass = $recoverPass; return $this->recoverPass; } static function canUpload($doNotCheckPlugins = false) { global $global, $config, $advancedCustomUser; if (Permissions::canModerateVideos()) { return true; } if (User::isAdmin()) { return true; } if (empty($doNotCheckPlugins) && !AVideoPlugin::userCanUpload(User::getId())) { return false; } if (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && !User::isVerified()) { return false; } if ($config->getAuthCanUploadVideos()) { return self::isLogged(); } if (self::isLogged() && !empty($_SESSION['user']['canUpload'])) { return true; } return self::isAdmin(); } static function canViewChart() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canViewChart'])) { return true; } return self::isAdmin(); } static function canCreateMeet() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canCreateMeet'])) { return true; } return self::isAdmin(); } static function canComment() { global $global, $config, $advancedCustomUser; if (self::isAdmin()) { return true; } if (Permissions::canAdminComment()) { return true; } if ($config->getAuthCanComment()) { if (empty($advancedCustomUser->unverifiedEmailsCanNOTComment)) { return self::isLogged(); } else { return self::isVerified(); } } return false; } static function canSeeCommentTextarea() { global $global, $config; if (!$config->getAuthCanComment()) { if (!self::isAdmin()) { return false; } } return true; } function getUserGroups() { return $this->userGroups; } function setUserGroups($userGroups) { if (is_array($userGroups)) { $this->userGroups = $userGroups; } } function getIsAdmin() { return $this->isAdmin; } function getStatus() { return $this->status; } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ static function getTags($user_id) { $user = new User($user_id); $tags = array(); if ($user->getIsAdmin()) { $obj = new stdClass(); $obj->type = "info"; $obj->text = __("Admin"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "default"; $obj->text = __("Regular User"); $tags[] = $obj; } if ($user->getStatus() == "a") { $obj = new stdClass(); $obj->type = "success"; $obj->text = __("Active"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "danger"; $obj->text = __("Inactive"); $tags[] = $obj; } if ($user->getEmailVerified()) { $obj = new stdClass(); $obj->type = "success"; $obj->text = __("E-mail Verified"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "warning"; $obj->text = __("E-mail Not Verified"); $tags[] = $obj; } global $global; if (!empty($global['systemRootPath'])) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; } else { require_once 'userGroups.php'; } $groups = UserGroups::getUserGroups($user_id); foreach ($groups as $value) { $obj = new stdClass(); $obj->type = "warning"; $obj->text = $value['group_name']; $tags[] = $obj; } return $tags; } function getBackgroundURL() { global $global; $this->backgroundURL = self::getBackgroundURLFromUserID($this->id); return $this->backgroundURL; } static function getBackgroundURLFromUserID($users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); } global $global; $backgroundURL = "videos/userPhoto/background{$users_id}.jpg"; if (!file_exists($global['systemRootPath'] . $backgroundURL)) { $backgroundURL = "videos/userPhoto/background{$users_id}.png"; } if (!file_exists($global['systemRootPath'] . $backgroundURL)) { $backgroundURL = "view/img/background.jpg"; } return $backgroundURL; } function setBackgroundURL($backgroundURL) { $this->backgroundURL = strip_tags($backgroundURL); } function getChannelName() { if (empty($this->channelName)) { $this->channelName = self::_recommendChannelName($this->channelName); $this->save(); } return $this->channelName; } static function _getUserChannelName($users_id = 0) { global $global, $config; if (empty($users_id)) { $users_id = self::getId(); } $user = new User($users_id); if (empty($user)) { return false; } return $user->getChannelName(); } function getEmailVerified() { return intval($this->emailVerified); } static function validateChannelName($channelName) { return trim(preg_replace("/[^0-9A-Z_]/i", "", ucwords($channelName))); } /** * * @param type $channelName * @return boolean return true is is unique */ function setChannelName($channelName) { $channelName = self::validateChannelName($channelName); $user = static::getChannelOwner($channelName); if (!empty($user)) { // if the channel name exists and it is not from this user, rename the channel name if (empty($this->id) || $user['id'] != $this->id) { return false; } } $this->channelName = xss_esc($channelName); return true; } function setEmailVerified($emailVerified) { $this->emailVerified = (empty($emailVerified) || strtolower($emailVerified) === 'false') ? 0 : 1; } static function getChannelLink($users_id = 0) { global $global; $name = self::_getChannelName($users_id); if (empty($name)) { return false; } $link = "{$global['webSiteRootURL']}channel/" . urlencode($name); return $link; } static function getChannelLinkFromChannelName($channelName) { global $global; $link = "{$global['webSiteRootURL']}channel/" . urlencode($channelName); return $link; } static function _getChannelName($users_id = 0) { global $global, $config; if (empty($users_id)) { $users_id = self::getId(); } $user = new User($users_id); if (empty($user)) { return false; } if (empty($user->getChannelName())) { $name = $user->getBdId(); } else { $name = $user->getChannelName(); } return $name; } static function sendVerificationLink($users_id) { global $global, $advancedCustomUser; //Only send the verification email each 30 minutes if (!empty($_SESSION["sendVerificationLink"][$users_id]) && time() - $_SESSION["sendVerificationLink"][$users_id] > 1800) { _error_log("sendVerificationLink: Email already sent, we will wait 30 min {$users_id}"); return true; } $config = new Configuration(); $user = new User($users_id); $code = urlencode(static::createVerificationCode($users_id)); - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/PHPMailer.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/SMTP.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/Exception.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/PHPMailer.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/SMTP.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/Exception.php'; //Create a new PHPMailer instance if (!is_object($config)) { _error_log("sendVerificationLink: config is not a object " . json_encode($config)); return false; } $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); $email = $user->getEmail(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //$mail->SMTPDebug = 4; //Set who the message is to be sent from $mail->setFrom($contactEmail, $webSiteTitle); //Set who the message is to be sent to $mail->addAddress($email); //Set the subject line $mail->Subject = __('Please Verify Your E-mail ') . $webSiteTitle; $msg = sprintf(__("Hi %s"), $user->getName()); $msg .= "

" . __($advancedCustomUser->verificationMailTextLine1); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine2), $webSiteTitle); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine3), $webSiteTitle); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine4)); $msg .= "

" . " " . __("Verify") . ""; $mail->msgHTML($msg); $resp = $mail->send(); if (!$resp) { _error_log("sendVerificationLink Error Info: {$mail->ErrorInfo}"); } else { _session_start(); $_SESSION["sendVerificationLink"][$users_id] = time(); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } return false; } static function verifyCode($code) { global $global; $obj = static::decodeVerificationCode($code); $salt = hash('sha256', $global['salt']); if ($salt !== $obj->salt) { return false; } $user = new User($obj->users_id); $recoverPass = $user->getRecoverPass(); if ($recoverPass == $obj->recoverPass) { $user->setEmailVerified(1); return $user->save(); } return false; } static function createVerificationCode($users_id) { global $global; $obj = new stdClass(); $obj->users_id = $users_id; $obj->recoverPass = uniqid(); $obj->salt = hash('sha256', $global['salt']); $user = new User($users_id); $obj->recoverPass = $user->setRecoverPass($obj->recoverPass); $user->save(); return base64_encode(json_encode($obj)); } static function decodeVerificationCode($code) { $obj = json_decode(base64_decode($code)); return $obj; } function getFirst_name() { return $this->first_name; } function getLast_name() { return $this->last_name; } function getAddress() { return $this->address; } function getZip_code() { return $this->zip_code; } function getCountry() { return $this->country; } function getRegion() { return $this->region; } function getCity() { return $this->city; } function setFirst_name($first_name) { $this->first_name = $first_name; } function setLast_name($last_name) { $this->last_name = $last_name; } function setAddress($address) { $this->address = $address; } function setZip_code($zip_code) { $this->zip_code = $zip_code; } function setCountry($country) { $this->country = $country; } function setRegion($region) { $this->region = $region; } function setCity($city) { $this->city = $city; } static function getDocumentImage($users_id) { $row = static::getBlob($users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } static function saveDocumentImage($image, $users_id) { $row = static::saveBlob($image, $users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } static function getBlob($users_id, $type) { global $global; $sql = "SELECT * FROM users_blob WHERE users_id = ? AND `type` = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "is", array($users_id, $type)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $result; } static function saveBlob($blob, $users_id, $type) { global $global; $row = self::getBlob($users_id, $type); $null = NULL; if (!empty($row['id'])) { $sql = "UPDATE users_blob SET `blob` = ? , modified = now() WHERE id = ?"; $stmt = $global['mysqli']->prepare($sql); $stmt->bind_param('bi', $null, $row['id']); } else { $sql = "INSERT INTO users_blob (`blob`, users_id, `type`, modified, created) VALUES (?,?,?, now(), now())"; $stmt = $global['mysqli']->prepare($sql); $stmt->bind_param('bis', $null, $users_id, $type); } $stmt->send_long_data(0, $blob); return $stmt->execute(); } static function deleteBlob($users_id, $type) { global $global; $row = self::getBlob($users_id, $type); if (!empty($row['id'])) { $sql = "DELETE FROM users_blob "; $sql .= " WHERE id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($row['id'])); } _error_log("Id for table users_blob not defined for deletion"); return false; } function getDonationLink() { return $this->donationLink; } function getDonationLinkIfEnabled() { global $advancedCustomUser; if ($advancedCustomUser->allowDonationLink) { return $this->donationLink; } return false; } function setDonationLink($donationLink) { $this->donationLink = $donationLink; } static function donationLink() { if (self::isLogged()) { return $_SESSION['user']['donationLink']; } else { return false; } } static function loginFromRequest() { $inputJSON = url_get_contents('php://input'); $input = json_decode($inputJSON, TRUE); //convert JSON into array if (is_array($input)) { foreach ($input as $key => $value) { if (empty($_REQUEST[$key])) { $_REQUEST[$key] = $value; } } } if (!empty($_REQUEST['do_not_login'])) { return false; } if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); $user->login(false, !empty($_REQUEST['encodedPass'])); } } static function loginFromRequestToGet() { if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $return = "user={$_REQUEST['user']}&pass={$_REQUEST['pass']}"; if (!empty($_REQUEST['encodedPass'])) { $return .= "&encodedPass=" . intval($_REQUEST['encodedPass']); } return $return; } return ""; } static function getBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::buttonBlockUser($users_id); } static function getActionBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::actionButtonBlockUser($users_id); } static function userCanBlockUser($users_id, $ignoreIfIsAlreadyBLocked = false) { if (empty($users_id)) { return false; } if (!User::isLogged()) { return false; } if ($users_id == User::getId()) { return false; } if (empty($ignoreIfIsAlreadyBLocked)) { $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return false; } } return true; } static function userCanBlockUserWithReason($users_id, $ignoreIfIsAlreadyBLocked = false) { $obj = new stdClass(); $obj->result = false; $obj->msg = "Unkonw"; if (empty($users_id)) { $obj->msg = "Empty User ID"; return $obj; } if (!User::isLogged()) { $obj->msg = "You are not logged"; return $obj; } if ($users_id == User::getId()) { $obj->msg = "You cannot block your own video"; return $obj; } if (empty($ignoreIfIsAlreadyBLocked)) { $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { $obj->msg = "this user is already blocked"; return $obj; } } $obj->result = true; $obj->msg = "You can block"; return $obj; } static function hasBlockedUser($reported_users_id, $users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); } if (!self::userCanBlockUser($reported_users_id, true)) { return false; } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (!empty($report)) { return ReportVideo::isBlocked($reported_users_id, $users_id); } else { return false; } } function updateUserImages($params = array()) { $id = $this->id; $obj = new stdClass(); // Update Background Image if (isset($params['backgroundImg']) && $params['backgroundImg'] != '') { $background = url_get_contents($params['backgroundImg']); $ext = pathinfo(parse_url($params['backgroundImg'], PHP_URL_PATH), PATHINFO_EXTENSION); $allowed = array('jpg', 'jpeg', 'gif', 'png'); if (!in_array(strtolower($ext), $allowed)) { return "File extension error background Image, We allow only (" . implode(",", $allowed) . ")"; } $backgroundPath = "videos/userPhoto/tmp_background{$id}." . $ext; $oldfile = "videos/userPhoto/background{$id}.png"; $file = "videos/userPhoto/background{$id}.jpg"; if (!isset($global['systemRootPath'])) { $global['systemRootPath'] = '../../'; } $filePath = $global['systemRootPath'] . $backgroundPath; $updateBackground = file_put_contents($filePath, $background); convertImage($filePath, $global['systemRootPath'] . $file, 70); if (file_exists($filePath)) { unlink($filePath); } if (file_exists($oldfile)) { unlink($oldfile); } if ($updateBackground) { $obj->background = 'Background has been updated!'; } else { $obj->background = 'Error updating background.'; } $this->setBackgroundURL($file); } // Update Profile Image if (isset($params['profileImg']) && $params['profileImg'] != '') { $photo = url_get_contents($params['profileImg']); $photoPath = "videos/userPhoto/photo{$id}.png"; if (!isset($global['systemRootPath'])) { $global['systemRootPath'] = '../../'; } $filePath = $global['systemRootPath'] . $photoPath; if (file_exists($filePath)) { unlink($filePath); } $updateProfile = file_put_contents($filePath, $photo); if ($updateProfile) { $obj->profile = 'Profile has been updated!'; } else { $obj->profile = 'Error updating profile.'; } $this->setPhotoURL($photoPath); } $formats = "ssi"; $values[] = $this->photoURL; $values[] = $this->backgroundURL; $values[] = $this->id; $sql .= "UPDATE users SET " . "photoURL = ?, backgroundURL = ?, " . " modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, $formats, $values); $obj->save = $insert_row; // create/update data for photoURL / backgroundURL return $obj; } } diff --git a/objects/userAddNew.json.php b/objects/userAddNew.json.php index c510022b9..d09f636f7 100644 --- a/objects/userAddNew.json.php +++ b/objects/userAddNew.json.php @@ -1,75 +1,71 @@ forceLoginToBeTheEmail)){ +if (!empty($advancedCustomUser->forceLoginToBeTheEmail)) { $_POST['email'] = $_POST['user']; } -if(empty($_POST['id'])){ +if (empty($_POST['id'])) { _error_log("userAddNew.json.php: Adding a user"); -}else{ +} else { _error_log("userAddNew.json.php: Editing a user id = {$_POST['id']}"); } - $user = new User(@$_POST['id']); $user->setUser($_POST['user']); $user->setPassword($_POST['pass']); $user->setEmail($_POST['email']); $user->setName($_POST['name']); $user->setIsAdmin($_POST['isAdmin']); $user->setCanStream($_POST['canStream']); $user->setCanUpload($_POST['canUpload']); $user->setCanViewChart($_POST['canViewChart']); $user->setCanCreateMeet($_POST['canCreateMeet']); $user->setStatus($_POST['status']); $user->setEmailVerified($_POST['isEmailVerified']); $user->setAnalyticsCode($_POST['analyticsCode']); _error_log("userAddNew.json.php: set channel name = ({$_POST['channelName']})"); $unique = $user->setChannelName($_POST['channelName']); //identify what variables come from external plugins $userOptions=AVideoPlugin::getPluginUserOptions(); -if(is_array($userOptions)) -{ +if (is_array($userOptions)) { $externalOptions=array(); - foreach($userOptions as $uo => $id) - { - if(isset($_POST[$id])) - $externalOptions[$id]=$_POST[$id]; + foreach ($userOptions as $uo => $id) { + if (isset($_POST[$id])) { + $externalOptions[$id]=$_POST[$id]; + } } $user->setExternalOptions($externalOptions); } //save it - - -if(!empty($_POST['channelName']) && !$unique){ +if (!empty($_POST['channelName']) && !$unique) { _error_log("userAddNew.json.php: channel name already exits = ({$_POST['channelName']})"); $user->setChannelName(User::_recommendChannelName($_POST['channelName'])); _error_log("userAddNew.json.php: new channel name: ".$user->getChannelName()); } -if(empty($_POST['userGroups'])){ - if(empty($_POST['id']) && !empty($advancedCustomUser->userDefaultUserGroup->value)){ // for new users use the default usergroup +if (empty($_POST['userGroups'])) { + if (empty($_POST['id']) && !empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup $user->setUserGroups(array($advancedCustomUser->userDefaultUserGroup->value)); } -}else{ +} else { $user->setUserGroups($_POST['userGroups']); } _error_log("userAddNew.json.php: saving"); $users_id = $user->save(true); echo '{"status":"'.$users_id.'"}'; _error_log("userAddNew.json.php: saved users_id ($users_id)"); diff --git a/objects/userCreate.json.php b/objects/userCreate.json.php index cf84d2d6b..cad3d6c8d 100644 --- a/objects/userCreate.json.php +++ b/objects/userCreate.json.php @@ -1,95 +1,97 @@ $value) { $_POST[$key] = $value; } } $obj = new stdClass(); if (empty($ignoreCaptcha)) { if (empty($_POST['captcha'])) { $obj->error = __("The captcha is empty"); die(json_encode($obj)); } require_once $global['systemRootPath'] . 'objects/captcha.php'; $valid = Captcha::validation($_POST['captcha']); if (!$valid) { $obj->error = __("The captcha is wrong"); die(json_encode($obj)); } } // check if user already exists $userCheck = new User(0, $_POST['user'], false); if (!empty($userCheck->getBdId())) { $obj->error = __("User already exists"); die(json_encode($obj)); } if (!empty($advancedCustomUser->forceLoginToBeTheEmail)) { $_POST['email'] = $_POST['user']; } $_POST['email'] = trim(@$_POST['email']); if (!empty($advancedCustomUser->emailMustBeUnique)) { if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $obj->error = __("You must specify an valid email"); die(json_encode($obj)); } $userFromEmail = User::getUserFromEmail($_POST['email']); if (!empty($userFromEmail)) { $obj->error = __("Email already exists"); die(json_encode($obj)); } } if (empty($_POST['user']) || empty($_POST['pass']) || empty($_POST['email']) || empty($_POST['name'])) { $obj->error = __("You must fill all fields"); die(json_encode($obj)); } - if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $obj->error = __("Invalid Email"); die(json_encode($obj)); } $user = new User(0); $user->setUser($_POST['user']); $user->setPassword($_POST['pass']); $user->setEmail($_POST['email']); $user->setName($_POST['name']); $user->setCanUpload($config->getAuthCanUploadVideos()); $users_id = $user->save(); if (!empty($users_id)) { $cu = AVideoPlugin::loadPluginIfEnabled('CustomizeUser'); if (!empty($cu)) { CustomizeUser::setCanShareVideosFromUser($users_id, true); } if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup UserGroups::updateUserGroups($users_id, array($advancedCustomUser->userDefaultUserGroup->value), true); } AVideoPlugin::onUserSignup($users_id); } echo '{"status":"' . $users_id . '"}'; diff --git a/objects/userGroups.php b/objects/userGroups.php index b1e4d8fbc..d6cae0b70 100644 --- a/objects/userGroups.php +++ b/objects/userGroups.php @@ -1,397 +1,397 @@ group_name = $group_name; } else { // get data from id $this->load($id); } } private function load($id) { $user = self::getUserGroupsDb($id); if (empty($user)) return false; foreach ($user as $key => $value) { $this->$key = $value; } } static private function getUserGroupsDb($id) { global $global; $id = intval($id); $sql = "SELECT * FROM users_groups WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { $user = $data; } else { $user = false; } return $user; } function save() { global $global; if (empty($this->isAdmin)) { $this->isAdmin = "false"; } $formats = ""; $values = array(); $this->group_name = _substr($this->group_name, 0, 255); if (!empty($this->id)) { $sql = "UPDATE users_groups SET group_name = ?, modified = now() WHERE id = ?"; $formats = "si"; $values = array($this->group_name,$this->id); } else { $sql = "INSERT INTO users_groups ( group_name, created, modified) VALUES (?,now(), now())"; $formats = "s"; $values = array($this->group_name); } if(sqlDAL::writeSql($sql,$formats,$values)){ if (empty($this->id)) { $id = $global['mysqli']->insert_id; } else { $id = $this->id; } return $id; } else { return false; } } function delete() { if (!User::isAdmin()) { return false; } global $global; if (!empty($this->id)) { $sql = "DELETE FROM users_groups WHERE id = ?"; } else { return false; } return sqlDAL::writeSql($sql,"i",array($this->id)); } private function getUserGroup($id) { global $global; $id = intval($id); $sql = "SELECT * FROM users_groups WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { $category = $data; } else { $category = false; } return $category; } static function getAllUsersGroups() { global $global; $sql = "SELECT *," . " (SELECT COUNT(*) FROM videos_group_view WHERE users_groups_id = ug.id ) as total_videos, " . " (SELECT COUNT(*) FROM users_has_users_groups WHERE users_groups_id = ug.id ) as total_users " . " FROM users_groups as ug WHERE 1=1 "; $sql .= BootGrid::getSqlFromPost(array('group_name')); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $arr = array(); if ($res!=false) { foreach ($fullData as $row) { $arr[] = $row; } //$category = $res->fetch_all(MYSQLI_ASSOC); } else { $arr = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $arr; } - + static function getAllUsersGroupsArray() { global $global; $sql = "SELECT * FROM users_groups as ug WHERE 1=1 "; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $arr = array(); if ($res!=false) { foreach ($fullData as $row) { $arr[$row['id']] = $row['group_name']; } //$category = $res->fetch_all(MYSQLI_ASSOC); } else { $arr = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $arr; } static function getTotalUsersGroups() { global $global; $sql = "SELECT id FROM users_groups WHERE 1=1 "; $sql .= BootGrid::getSqlSearchFromPost(array('group_name')); $res = sqlDAL::readSql($sql); $numRows = sqlDAL::num_rows($res); sqlDAL::close($res); return $numRows; } function getGroup_name() { return $this->group_name; } function setGroup_name($group_name) { $this->group_name = $group_name; } - + static function getUserGroupByName($group_name, $refreshCache = false) { global $global; $sql = "SELECT * FROM users_groups WHERE group_name = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($group_name),$refreshCache); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { $category = $data; } else { $category = false; } return $category; } static function getOrCreateUserGroups($group_name){ $group_name = trim($group_name); $group_name = _substr($group_name, 0, 255); if(empty($group_name)){ return false; } $group = self::getUserGroupByName($group_name, true); if(empty($group)){ $g = new UserGroups(0, $group_name); return $g->save(); }else{ return $group['id']; } } // for users static function updateUserGroups($users_id, $array_groups_id, $byPassAdmin=false){ if (!$byPassAdmin && !Permissions::canAdminUsers()) { return false; } if (!is_array($array_groups_id)) { return false; } self::deleteGroupsFromUser($users_id, $byPassAdmin); global $global; $array_groups_id = array_unique($array_groups_id); $sql = "INSERT INTO users_has_users_groups ( users_id, users_groups_id) VALUES (?,?)"; foreach ($array_groups_id as $value) { $value = intval($value); sqlDAL::writeSql($sql,"ii",array($users_id,$value)); } return true; } static function getUserGroups($users_id) { global $global; $res = sqlDAL::readSql("SHOW TABLES LIKE 'users_has_users_groups'"); $result = sqlDAL::num_rows($res); sqlDAL::close($res); if (empty($result)) { $_GET['error'] = "You need to update your system to ver 2.3"; return array(); } if (empty($users_id)) { return array(); } $sql = "SELECT uug.*, ug.* FROM users_groups ug" . " LEFT JOIN users_has_users_groups uug ON users_groups_id = ug.id WHERE users_id = ? "; - + $ids = AVideoPlugin::getDynamicUserGroupsId($users_id); if(!empty($ids) && is_array($ids)){ $ids = array_unique($ids); $sql .= " OR ug.id IN ('". implode("','", $ids)."') "; } //var_dump($ids);echo $sql;exit; $res = sqlDAL::readSql($sql,"i",array($users_id)); $fullData = sqlDal::fetchAllAssoc($res); sqlDAL::close($res); $arr = array(); $doNotRepeat = array(); if ($res!=false) { foreach ($fullData as $row) { if(in_array($row['id'], $doNotRepeat)){ continue; } $doNotRepeat[] = $row['id']; $arr[] = $row; } } else { $arr = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $arr; } static private function deleteGroupsFromUser($users_id, $byPassAdmin=false){ if (!$byPassAdmin && !User::isAdmin()) { return false; } global $global; if (!empty($users_id)) { $sql = "DELETE FROM users_has_users_groups WHERE users_id = ?"; } else { return false; } return sqlDAL::writeSql($sql,"i",array($users_id)); } static function getVideoGroupsViewId($videos_id, $users_groups_id) { if(empty($videos_id)){ return false; } if(empty($users_groups_id)){ return false; } global $global; $sql = "SELECT id FROM videos_group_view WHERE videos_id = ? AND users_groups_id = ? LIMIT 1 "; $res = sqlDAL::readSql($sql,"ii",array($videos_id, $users_groups_id)); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($data)) { return $data['id']; } else { return 0; } - + } static function addVideoGroups($videos_id, $users_groups_id) { if (!User::canUpload()) { return false; } global $global; - + if(self::getVideoGroupsViewId($videos_id, $users_groups_id)){ return false; } $sql = "INSERT INTO videos_group_view ( videos_id, users_groups_id) VALUES (?,?)"; $value = intval($value); $response = sqlDAL::writeSql($sql,"ii",array($videos_id,$users_groups_id)); - + if($response){ Video::clearCache($videos_id); } return $response; } - + static function deleteVideoGroups($videos_id, $users_groups_id) { if (!User::canUpload()) { return false; } - + $sql = "DELETE FROM videos_group_view WHERE videos_id = ? AND users_groups_id = ?"; $response = sqlDAL::writeSql($sql,"ii",array($videos_id, $users_groups_id)); - + if($response){ Video::clearCache($videos_id); } return $response; } - + static function updateVideoGroups($videos_id, $array_groups_id) { if (!User::canUpload()) { return false; } if (!is_array($array_groups_id)) { return false; } self::deleteGroupsFromVideo($videos_id); global $global; $sql = "INSERT INTO videos_group_view ( videos_id, users_groups_id) VALUES (?,?)"; foreach ($array_groups_id as $value) { $value = intval($value); sqlDAL::writeSql($sql,"ii",array($videos_id,$value)); } return true; } static function getVideoGroups($videos_id) { if(empty($videos_id)){ return array(); } global $global; //check if table exists if not you need to update $sql = "SELECT 1 FROM `videos_group_view` LIMIT 1"; $res = sqlDAL::readSql($sql); sqlDAL::close($res); if (!$res) { if (User::isAdmin()) { $_GET['error'] = "You need to Update AVideo to version 2.3 Click here"; } return array(); } $sql = "SELECT v.*, ug.*FROM videos_group_view as v " . " LEFT JOIN users_groups as ug ON users_groups_id = ug.id WHERE videos_id = ? "; $res = sqlDAL::readSql($sql,"i",array($videos_id)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $arr = array(); if ($res!=false) { foreach ($fullData as $row) { $arr[] = $row; } } else { $arr = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $arr; } static private function deleteGroupsFromVideo($videos_id){ if (!User::canUpload()) { return false; } global $global; if (!empty($videos_id)) { $sql = "DELETE FROM videos_group_view WHERE videos_id = ?"; } else { return false; } return sqlDAL::writeSql($sql,"i",array($videos_id)); } } diff --git a/objects/userRecoverPass.php b/objects/userRecoverPass.php index 20f6ebd4f..b767d6dbd 100644 --- a/objects/userRecoverPass.php +++ b/objects/userRecoverPass.php @@ -1,179 +1,179 @@ getEmail())) { $recoverPass = md5(rand()); $recoverPass = $user->setRecoverPass($recoverPass); if (!empty($_POST['captcha']) && $user->save()) { require_once 'captcha.php'; $valid = Captcha::validation($_POST['captcha']); if ($valid) { - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/PHPMailer.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/SMTP.php'; - require_once $global['systemRootPath'] . 'objects/PHPMailer/phpmailer/src/Exception.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/PHPMailer.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/SMTP.php'; + require_once $global['systemRootPath'] . 'objects/phpmailer/phpmailer/src/Exception.php'; //Create a new PHPMailer instance $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //Set who the message is to be sent from $mail->setFrom($config->getContactEmail(), $config->getWebSiteTitle()); //Set who the message is to be sent to $mail->addAddress($user->getEmail()); //Set the subject line $mail->Subject = 'Recover Pass from ' . $config->getWebSiteTitle(); $msg = __("You asked for a recover link, click on the provided link") . " " . __("Reset password") . ""; $mail->msgHTML($msg); //send the message, check for errors if (!$mail->send()) { $obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo; } else { $obj->success = __("Message sent"); } } else { $obj->error = __("Your code is not valid"); } } else { $obj->error = __("Recover password could not be saved!"); } } else { $obj->error = __("You do not have an e-mail"); } die(json_encode($obj)); } else { ?> <?php echo __("Recover Password") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?>
getRecoverPass() != $_GET['recoverpass']) { ?>
error = true; -$obj->msg = "Unknown error"; +$obj->error = true; +$obj->msg = "Unknown error"; if (!empty($_GET['users_id'])) { $user = new User($_GET['users_id']); $verified = $user->getEmailVerified(); if(empty($verified)){ if(User::sendVerificationLink($_GET['users_id'])){ - $obj->error = false; - $obj->msg = __("Verification Sent"); + $obj->error = false; + $obj->msg = __("Verification Sent"); } }else{ $obj->msg = __("Already verified"); } }else if(!empty($_GET['code'])){ $result = User::verifyCode($_GET['code']); if($result){ $msg = __("Email Verified"); header("Location: {$global['webSiteRootURL']}?success={$msg}"); }else{ $msg = __("Email verification error"); header("Location: {$global['webSiteRootURL']}?error={$msg}"); } } header('Content-Type: application/json'); die(json_encode($obj)); \ No newline at end of file diff --git a/objects/video.php b/objects/video.php index f523cf024..a3c312d9b 100644 --- a/objects/video.php +++ b/objects/video.php @@ -1,4025 +1,4023 @@ 'active', 'i' => 'inactive', 'e' => 'encoding', 'x' => 'encoding error', 'd' => 'downloading', 'xmp4' => 'encoding mp4 error', 'xwebm' => 'encoding webm error', 'xmp3' => 'encoding mp3 error', 'xogg' => 'encoding ogg error', 'ximg' => 'get image error', 't' => 'transfering'); public static $rratingOptions = array('', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma'); //ver 3.4 private $youtubeId; public static $typeOptions = array('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'image', 'zip', 'notfound', 'blockedUser'); public function __construct($title = "", $filename = "", $id = 0) { global $global; $this->rotation = 0; $this->zoom = 1; if (!empty($id)) { $this->load($id); } if (!empty($title)) { $this->setTitle($title); } if (!empty($filename)) { $this->filename = $filename; } } public function addView($currentTime = 0) { global $global; if (empty($this->id)) { return false; } $sql = "UPDATE videos SET views_count = views_count+1, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { $obj = new stdClass(); $obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime); $obj->videos_id = $this->id; $this->views_count++; AVideoPlugin::addView($this->id, $this->views_count); return $obj; } else { die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } public function updateViewsCount($total) { global $global; if (empty($this->id)) { return false; } $total = intval($total); if ($total<0) { return false; } $sql = "UPDATE videos SET views_count = {$total}, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { return $insert_row; } else { die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } public function addViewPercent($percent = 25) { global $global; if (empty($this->id)) { return false; } $sql = "UPDATE videos SET views_count_{$percent} = IFNULL(views_count_{$percent}, 0)+1, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { return true; } else { die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } // allow users to count a view again in case it is refreshed public static function unsetAddView($videos_id) { // allow users to count a view again in case it is refreshed if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) { _session_start(); unset($_SESSION['addViewCount'][$videos_id]); } } public function load($id) { $video = self::getVideoLight($id); if (empty($video)) { return false; } foreach ($video as $key => $value) { $this->$key = $value; } } public function getEncoderURL() { return $this->encoderURL; } public function getFilepath() { return $this->filepath; } public function getFilesize() { return intval($this->filesize); } public function setEncoderURL($encoderURL) { if (filter_var($encoderURL, FILTER_VALIDATE_URL) !== false) { $this->encoderURL = $encoderURL; } } public function setFilepath($filepath) { $this->filepath = $filepath; } public function setFilesize($filesize) { $this->filesize = intval($filesize); } public function setUsers_id($users_id) { $this->users_id = $users_id; } public function getSites_id() { return $this->sites_id; } public function setSites_id($sites_id) { $this->sites_id = $sites_id; } public function getVideo_password() { return trim($this->video_password); } public function setVideo_password($video_password) { $this->video_password = trim($video_password); } public function save($updateVideoGroups = false, $allowOfflineUser = false) { global $advancedCustom; global $global; if (!User::isLogged() && !$allowOfflineUser) { _error_log('Video::save permission denied to save'); return false; } if (empty($this->title)) { $this->title = uniqid(); } $this->clean_title = substr($this->clean_title, 0, 187); if (empty($this->clean_title)) { $this->setClean_title($this->title); } $this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id); if (empty($this->status)) { $this->status = 'e'; } if (empty($this->type) || !in_array($this->type, self::$typeOptions)) { $this->type = 'video'; } if (empty($this->isSuggested)) { $this->isSuggested = 0; } else { $this->isSuggested = 1; } if (empty($this->categories_id)) { $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); $category = Category::getCategoryDefault(); $categories_id = $category['id']; if (empty($categories_id)) { $categories_id = 'NULL'; } if ($p) { $this->categories_id = $p->getCategoryId(); } else { $this->categories_id = $categories_id; } if (empty($this->categories_id)) { $this->categories_id = $categories_id; } } // check if category exists $cat = new Category($this->categories_id); if (empty($cat->getName())) { $catDefault = Category::getCategoryDefault(); $this->categories_id = $catDefault['id']; } $this->setTitle($global['mysqli']->real_escape_string(trim($this->title))); $this->description = ($global['mysqli']->real_escape_string($this->description)); if (forbiddenWords($this->title) || forbiddenWords($this->description)) { return false; } if (empty($this->users_id)) { $this->users_id = User::getId(); } $this->next_videos_id = intval($this->next_videos_id); if (empty($this->next_videos_id)) { $this->next_videos_id = 'NULL'; } $this->sites_id = intval($this->sites_id); if (empty($this->sites_id)) { $this->sites_id = 'NULL'; } $this->serie_playlists_id = intval($this->serie_playlists_id); if (empty($this->serie_playlists_id)) { $this->serie_playlists_id = 'NULL'; } if (empty($this->filename)) { $this->filename = $this->type . "_" . uniqid(); } $this->can_download = intval($this->can_download); $this->can_share = intval($this->can_share); $this->only_for_paid = intval($this->only_for_paid); $this->filesize = intval($this->filesize); $this->rate = floatval($this->rate); if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) { $this->videoLink = ''; if ($this->type == 'embed') { $this->type = 'video'; } } if (!empty($this->id)) { if (!$this->userCanManageVideo() && !$allowOfflineUser && !Permissions::canModerateVideos()) { header('Content-Type: application/json'); die('{"error":"3 ' . __("Permission denied") . '"}'); } $sql = "UPDATE videos SET title = '{$this->title}',clean_title = '{$this->clean_title}'," . " filename = '{$this->filename}', categories_id = '{$this->categories_id}', status = '{$this->status}'," . " description = '{$this->description}', duration = '{$this->duration}', type = '{$this->type}', videoDownloadedLink = '{$this->videoDownloadedLink}', youtubeId = '{$this->youtubeId}', videoLink = '{$this->videoLink}', next_videos_id = {$this->next_videos_id}, isSuggested = {$this->isSuggested}, users_id = {$this->users_id}, " . " trailer1 = '{$this->trailer1}', trailer2 = '{$this->trailer2}', trailer3 = '{$this->trailer3}', rate = '{$this->rate}', can_download = '{$this->can_download}', can_share = '{$this->can_share}', only_for_paid = '{$this->only_for_paid}', rrating = '{$this->rrating}', externalOptions = '{$this->externalOptions}', sites_id = {$this->sites_id}, serie_playlists_id = {$this->serie_playlists_id} , video_password = '{$this->video_password}', " . " encoderURL = '{$this->encoderURL}', filepath = '{$this->filepath}' , filesize = '{$this->filesize}' , modified = now()" . " WHERE id = {$this->id}"; } else { $sql = "INSERT INTO videos " . "(title,clean_title, filename, users_id, categories_id, status, description, duration,type,videoDownloadedLink, next_videos_id, created, modified, videoLink, can_download, can_share, only_for_paid, rrating, externalOptions, sites_id, serie_playlists_id, video_password, encoderURL, filepath , filesize) values " . "('{$this->title}','{$this->clean_title}', '{$this->filename}', {$this->users_id},{$this->categories_id}, '{$this->status}', '{$this->description}', '{$this->duration}', '{$this->type}', '{$this->videoDownloadedLink}', {$this->next_videos_id},now(), now(), '{$this->videoLink}', '{$this->can_download}', '{$this->can_share}','{$this->only_for_paid}', '{$this->rrating}', '$this->externalOptions', {$this->sites_id}, {$this->serie_playlists_id}, '{$this->video_password}', '{$this->encoderURL}', '{$this->filepath}', '{$this->filesize}')"; } $insert_row = sqlDAL::writeSql($sql); if ($insert_row) { _error_log("Video::save ({$this->title}) Saved id = {$insert_row} "); Category::clearCacheCount(); if (empty($this->id)) { $id = $global['mysqli']->insert_id; $this->id = $id; // check if needs to add the video in a user group $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); if ($p) { $updateVideoGroups = true; $this->videoGroups = $p->getUserGroupsArray(); } } else { $id = $this->id; } ObjectYPT::deleteCache("getItemprop{$this->id}"); ObjectYPT::deleteCache("getLdJson{$this->id}"); ObjectYPT::deleteCache("getVideoTags{$this->id}"); self::deleteTagsAsync($this->id); if ($updateVideoGroups) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; // update the user groups UserGroups::updateVideoGroups($id, $this->videoGroups); } // I am not sure what is it for //Video::autosetCategoryType($id); if (!empty($this->old_categories_id)) { //Video::autosetCategoryType($this->old_categories_id); } self::clearCache($this->id); return $id; } else { _error_log('Video::save ' . $sql . ' Save Video Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); return false; } } /* static function autosetCategoryType($catId) { global $global, $config; if ($config->currentVersionLowerThen('5.01')) { return false; } $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $catTypeCache = sqlDAL::fetchAssoc($res); sqlDAL::close($res); $videoFound = false; $audioFound = false; if ($catTypeCache) { // 3 means auto if ($catTypeCache['manualSet'] == "0") { // start incremental search and save $sql = "SELECT * FROM `videos` WHERE categories_id = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult as $row) { if ($row['type'] == "audio") { // echo "found audio"; $audioFound = true; } else if ($row['type'] == "video") { //echo "found video"; $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT * FROM `categories` WHERE parentId = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { //$tmpVid = $res->fetch_assoc(); foreach ($fullResult as $row) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($row['parentId'])); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { // echo "found audio"; $audioFound = true; } else if ($row['type'] == "video") { //echo "found video"; $videoFound = true; } } } } } $sql = "UPDATE `category_type_cache` SET `type` = '"; if (($videoFound) && ($audioFound)) { $sql .= "0"; } else if ($audioFound) { $sql .= "1"; } else if ($videoFound) { $sql .= "2"; } else { $sql .= "0"; } $sql .= "' WHERE `category_type_cache`.`categoryId` = ?;"; sqlDAL::writeSql($sql, "i", array($catId)); } } else { // start incremental search and save - and a lot of this redundant stuff in a method.. $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } else if ($row['type'] == "video") { $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT parentId FROM `categories` WHERE parentId = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $cat) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } else if ($row['type'] == "video") { $videoFound = true; } } } } } } $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $exist = sqlDAL::fetchAssoc($res); sqlDAL::close($res); $sqlType = 99; if (($videoFound) && ($audioFound)) { $sqlType = 0; } else if ($audioFound) { $sqlType = 1; } else if ($videoFound) { $sqlType = 2; } $values = array(); if (empty($exist)) { $sql = "INSERT INTO `category_type_cache` (`categoryId`, `type`) VALUES (?, ?);"; $values = array($catId, $sqlType); } else { $sql = "UPDATE `category_type_cache` SET `type` = ? WHERE `category_type_cache`.`categoryId` = ?;"; $values = array($sqlType, $catId); } sqlDAL::writeSql($sql, "ii", $values); } } */ // i would like to simplify the big part of the method above in this method, but won't work as i want. public static function internalAutoset($catId, $videoFound, $audioFound) { global $config; if ($config->currentVersionLowerThen('5.01')) { return false; } $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } elseif ($row['type'] == "video") { $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT parentId,categories_id FROM `categories` WHERE parentId = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $cat) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult as $row) { if ($row['type'] == "audio") { $audioFound = true; } elseif ($row['type'] == "video") { $videoFound = true; } } } } } } return array($videoFound, audioFound); } public function setClean_title($clean_title) { if (preg_match("/video-automatically-booked/i", $clean_title) && !empty($this->clean_title)) { return false; } $this->clean_title = cleanURLName($clean_title); } public function setDuration($duration) { $this->duration = $duration; } public function getDuration() { return $this->duration; } public function getIsSuggested() { return $this->isSuggested; } public function setIsSuggested($isSuggested) { if (empty($isSuggested) || $isSuggested === "false") { $this->isSuggested = 0; } else { $this->isSuggested = 1; } } public function setStatus($status) { if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET status = ?, modified = now() WHERE id = ? "; $res = sqlDAL::writeSql($sql, 'si', array($status, $this->id)); if ($global['mysqli']->errno != 0) { die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } self::deleteTagsAsync($this->id); } $this->status = $status; } public function setType($type, $force = true) { if ($force || empty($this->type)) { $this->type = $type; } } public function setRotation($rotation) { $saneRotation = intval($rotation) % 360; if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET rotation = '{$saneRotation}', modified = now() WHERE id = {$this->id} "; $res = sqlDAL::writeSql($sql); if ($global['mysqli']->errno != 0) { die('Error on update Rotation: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } $this->rotation = $saneRotation; } public function getRotation() { return $this->rotation; } public function getUsers_id() { return $this->users_id; } public function setZoom($zoom) { $saneZoom = abs(floatval($zoom)); if ($saneZoom < 0.1 || $saneZoom > 10) { die('Zoom level must be between 0.1 and 10'); } if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET zoom = '{$saneZoom}', modified = now() WHERE id = {$this->id} "; $res = sqlDAL::writeSql($sql); if ($global['mysqli']->errno != 0) { die('Error on update Zoom: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } $this->zoom = $saneZoom; } public function getZoom() { return $this->zoom; } public static function getUserGroupsCanSeeSQL() { global $global; if (Permissions::canModerateVideos()) { return ""; } $sql = " (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0 "; if (User::isLogged()) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; $userGroups = UserGroups::getUserGroups(User::getId()); $groups_id = array(); foreach ($userGroups as $value) { $groups_id[] = $value['id']; } if (!empty($groups_id)) { $sql = " (({$sql}) OR ((SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id AND users_groups_id IN ('" . implode("','", $groups_id) . "') ) > 0)) "; } } return " AND " . $sql; } public static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true) { global $global, $config, $advancedCustom; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $id = intval($id); if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); } } $sql = "SELECT u.*, v.*, " . " nv.title as next_title," . " nv.clean_title as next_clean_title," . " nv.filename as next_filename," . " nv.id as next_id," . " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description,c.nextVideoOrder as category_order, v.created as videoCreation, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes "; if (User::isLogged()) { $sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote "; } else { $sql .= ", 0 as myVote "; } $sql .= " FROM videos as v " . "LEFT JOIN categories c ON categories_id = c.id " . "LEFT JOIN users u ON v.users_id = u.id " . "LEFT JOIN videos nv ON v.next_videos_id = nv.id " . " WHERE 1=1 "; if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } if (!empty($id)) { $sql .= " AND v.id = '$id' "; } $sql .= AVideoPlugin::getVideoWhereClause(); $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL(); } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } elseif ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($status == "viewable") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['catName'])) { $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))"; } if (empty($id) && !empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); if (!empty($user['id'])) { $sql .= " AND v.users_id = '{$user['id']}' "; } } if (!empty($_GET['search'])) { $_POST['searchPhrase'] = $_GET['search']; } if (!empty($_POST['searchPhrase'])) { if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR"); $sql .= ")"; } else { $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description')); } } if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } // replace random based on this $firstClauseLimit = ""; if (empty($id)) { if (empty($random) && !empty($_GET['videoName'])) { $sql .= " AND v.clean_title = '{$_GET['videoName']}' "; } elseif (!empty($random)) { $sql .= " AND v.id != {$random} "; $rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly)); $rand = ($rand - 2) < 0 ? 0 : $rand - 2; $firstClauseLimit = "$rand, "; //$sql .= " ORDER BY RAND() "; } elseif ($suggestedOnly && empty($_GET['videoName']) && empty($_GET['search']) && empty($_GET['searchPhrase'])) { $sql .= " AND v.isSuggested = 1 "; $rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly)); $rand = ($rand - 2) < 0 ? 0 : $rand - 2; $firstClauseLimit = "$rand, "; //$sql .= " ORDER BY RAND() "; } elseif (!empty($_GET['v']) && is_numeric($_GET['v'])) { $vid = intval($_GET['v']); $sql .= " AND v.id = {$vid} "; } else { $sql .= " ORDER BY v.Created DESC "; } } if (strpos($sql, 'v.id IN') === false && strpos(strtolower($sql), 'limit') === false) { $sql .= " LIMIT {$firstClauseLimit}1"; } //echo $sql, "
";//exit; $res = sqlDAL::readSql($sql); $video = sqlDAL::fetchAssoc($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($video) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getVideo($id, $status, $ignoreGroup, $random, $suggestedOnly, $showUnlisted, $ignoreTags, $activeUsersOnly); $_GET['channelName'] = $channelName; return $return; } sqlDAL::close($res); if ($res != false) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; if (!empty($video)) { $video['category'] = xss_esc_back($video['category']); $video['groups'] = UserGroups::getVideoGroups($video['id']); $video['title'] = UTF8encode($video['title']); $video['description'] = UTF8encode($video['description']); $video['progress'] = self::getVideoPogressPercent($video['id']); $video['isFavorite'] = self::isFavorite($video['id']); $video['isWatchLater'] = self::isWatchLater($video['id']); $video['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); $video['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); if (empty($video['filesize']) && ($video['type'] == "video" || $video['type'] == "audio")) { $video['filesize'] = Video::updateFilesize($video['id']); } if (!$ignoreTags) { $video['tags'] = self::getTags($video['id']); } if (!empty($video['externalOptions'])) { $video['externalOptions'] = json_decode($video['externalOptions']); } else { $video['externalOptions'] = new stdClass(); } $video['descriptionHTML'] = strip_tags($video['description']) === $video['description'] ? nl2br(textToLink(htmlentities($video['description']))) : $video['description']; if (!$ignoreTags && AVideoPlugin::isEnabledByName("VideoTags")) { $video['videoTags'] = Tags::getAllFromVideosId($video['id']); $video['videoTagsObject'] = Tags::getObjectFromVideosId($video['id']); } unset($video['password']); unset($video['recoverPass']); } } else { $video = false; } return $video; } public static function getVideoLight($id) { global $global, $config; $id = intval($id); $sql = "SELECT * FROM videos WHERE id = '$id' LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } public static function getTotalVideosSizeFromUser($users_id) { global $global, $config; $users_id = intval($users_id); $sql = "SELECT sum(filesize) as total FROM videos WHERE 1=1 "; if (!empty($users_id)) { $sql .= " AND users_id = '$users_id'"; } $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return intval($video['total']); } public static function getTotalVideosFromUser($users_id) { global $global, $config; $users_id = intval($users_id); $sql = "SELECT count(*) as total FROM videos WHERE 1=1 "; if (!empty($users_id)) { $sql .= " AND users_id = '$users_id'"; } $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return intval($video['total']); } public static function getVideoFromFileName($fileName, $ignoreGroup = false, $ignoreTags = false) { global $global; if (empty($fileName)) { return false; } $parts = explode("/", $fileName); if (!empty($parts[0])) { $fileName = $parts[0]; } $fileName = self::getCleanFilenameFromFile($fileName); $sql = "SELECT id FROM videos WHERE filename = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($fileName)); if ($res != false) { $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($video['id'])) { return self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags); } } return false; } public static function getVideoFromFileNameLight($fileName) { global $global; $fileName = self::getCleanFilenameFromFile($fileName); if (empty($fileName)) { return false; } $sql = "SELECT * FROM videos WHERE filename = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($fileName), true); if ($res != false) { $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } return false; } public static function getVideoFromCleanTitle($clean_title) { // for some reason in some servers (CPanel) we got the error "Error while sending QUERY packet centos on a select" // even increasing the max_allowed_packet it only goes away when close and reopen the connection global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; $global['mysqli']->close(); _mysql_connect(); if (!empty($global['mysqli_charset'])) { $global['mysqli']->set_charset($global['mysqli_charset']); } $sql = "SELECT id FROM videos WHERE clean_title = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($clean_title)); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { return self::getVideo($video['id'], "", true, false, false, true); //$video['groups'] = UserGroups::getVideoGroups($video['id']); } else { return false; } } /** * * @global type $global * @param type $status * @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results * @param type $ignoreGroup * @param type $videosArrayId an array with videos to return (for filter only) * @return boolean */ public static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false) { global $global, $config, $advancedCustom; if ($config->currentVersionLowerThen('5')) { return false; } if (!empty($_POST['sort']['suggested'])) { $suggestedOnly = true; } if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})"); $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__); } } $status = str_replace("'", "", $status); $sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes " . " FROM videos as v " . " LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 1=1 "; $blockedUsers = self::getBlockedUsersIdsArray(); if (!empty($blockedUsers)) { $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; } if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $uid = intval(User::getId()); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $uid = intval($showOnlyLoggedUserVideos); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { TimeLogStart("video::getAllVideos::getAllVideosExcludeVideosIDArray"); $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } TimeLogEnd("video::getAllVideos::getAllVideosExcludeVideosIDArray", __LINE__); } if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL(); } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } elseif ($_SESSION['type'] == 'videoOnly') { $sql .= " AND (v.type = 'video')"; } elseif ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif ($status == "publicOnly") { $sql .= " AND v.status = 'a' AND (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['catName'])) { $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))"; } if (!empty($_GET['search'])) { $_POST['searchPhrase'] = $_GET['search']; } if (!empty($_GET['modified'])) { $_GET['modified'] = str_replace("'", "", $_GET['modified']); $sql .= " AND v.modified >= '{$_GET['modified']}'"; } if (!empty($_POST['searchPhrase'])) { if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR"); $sql .= ")"; } else { $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description')); } } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; $sort = @$_POST['sort']; unset($_POST['sort']); $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); if (strpos(strtolower($sql), 'limit') === false) { $sql .= " LIMIT 60 "; } $_POST['sort'] = $sort; } elseif (!isset($_POST['sort']['trending']) && !isset($_GET['sort']['trending'])) { $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); } else { unset($_POST['sort']['trending']); unset($_GET['sort']['trending']); $rows = array(); if (!empty($_REQUEST['current']) && $_REQUEST['current'] == 1) { $rows = VideoStatistic::getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); } $ids = array(); foreach ($rows as $row) { $ids[] = $row['id']; } if (!empty($ids)) { $sql .= " ORDER BY FIND_IN_SET(v.id, '" . implode(",", $ids) . "') DESC, likes DESC "; } else { $sql .= " ORDER BY likes DESC "; } $sql .= ObjectYPT::getSqlLimit(); } if (strpos(strtolower($sql), 'limit') === false) { if (!empty($_GET['limitOnceToOne'])) { $sql .= " LIMIT 1"; unset($_GET['limitOnceToOne']); } $_REQUEST['rowCount'] = getRowCount(); if (!empty($_REQUEST['rowCount'])) { $sql .= " LIMIT {$_REQUEST['rowCount']}"; } else { _error_log("getAllVideos without limit " . json_encode(debug_backtrace())); if (empty($global['limitForUnlimitedVideos'])) { $global['limitForUnlimitedVideos'] = 100; } if ($global['limitForUnlimitedVideos'] > 0) { $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; } } } //echo $sql;exit; //_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly, $suggestedOnly); $_GET['channelName'] = $channelName; return $return; } sqlDAL::close($res); $videos = array(); if ($res != false) { require_once 'userGroups.php'; TimeLogStart("video::getAllVideos foreach"); foreach ($fullData as $row) { unset($row['password']); unset($row['recoverPass']); if (!self::canEdit($row['id'])) { if (!empty($row['video_password'])) { $row['video_password'] = 1; } else { $row['video_password'] = 0; } } if ($getStatistcs) { TimeLogStart("video::getAllVideos getStatistcs"); $previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days")); $previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days")); $today = date('Y-m-d 23:59:59'); $row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']); $row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today); $row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today); $row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today); $row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true); TimeLogEnd("video::getAllVideos getStatistcs", __LINE__); } TimeLogStart("video::getAllVideos otherInfo"); $otherInfocachename = "otherInfo{$row['id']}"; $otherInfo = object_to_array(ObjectYPT::getCache($otherInfocachename), 600); if (empty($otherInfo)) { $otherInfo = array(); $otherInfo['category'] = xss_esc_back($row['category']); $otherInfo['groups'] = UserGroups::getVideoGroups($row['id']); $otherInfo['tags'] = self::getTags($row['id']); $otherInfo['title'] = UTF8encode($row['title']); $otherInfo['description'] = UTF8encode($row['description']); $otherInfo['descriptionHTML'] = self::htmlDescription($otherInfo['description']); if (empty($row['filesize'])) { $otherInfo['filesize'] = Video::updateFilesize($row['id']); } ObjectYPT::setCache($otherInfocachename, $otherInfo); } foreach ($otherInfo as $key => $value) { $row[$key] = $value; } $row['progress'] = self::getVideoPogressPercent($row['id']); $row['isFavorite'] = self::isFavorite($row['id']); $row['isWatchLater'] = self::isWatchLater($row['id']); $row['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); $row['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); TimeLogEnd("video::getAllVideos otherInfo", __LINE__); TimeLogStart("video::getAllVideos getAllVideosArray"); $row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id'])); TimeLogEnd("video::getAllVideos getAllVideosArray", __LINE__); $videos[] = $row; } TimeLogEnd("video::getAllVideos foreach", __LINE__); //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } public static function htmlDescription($description) { if (strip_tags($description) != $description) { return $description; } else { return nl2br(textToLink(htmlentities($description))); } } public static function isFavorite($videos_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::isVideoOnFavorite($videos_id, User::getId()); } return false; } public static function isSerie($videos_id) { $v = new Video("", "", $videos_id); return !empty($v->getSerie_playlists_id()); } public static function isWatchLater($videos_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::isVideoOnWatchLater($videos_id, User::getId()); } return false; } public static function getFavoriteIdFromUser($users_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::getFavoriteIdFromUser($users_id); } return false; } public static function getWatchLaterIdFromUser($users_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::getWatchLaterIdFromUser($users_id); } return false; } public static function updateFilesize($videos_id) { global $config; if ($config->currentVersionLowerThen('8.5')) { return false; } TimeLogStart("Video::updateFilesize {$videos_id}"); ini_set('max_execution_time', 300); // 5 set_time_limit(300); $video = new Video("", "", $videos_id); $filename = $video->getFilename(); if (empty($filename) || !($video->getType() == "video" || $video->getType() == "audio" || $video->getType() == "zip" || $video->getType() == "image")) { //_error_log("updateFilesize: Not updated, this filetype is ".$video->getType()); return false; } $filesize = getUsageFromFilename($filename); if (empty($filesize)) { $obj = AVideoPlugin::getObjectDataIfEnabled("DiskUploadQuota"); if (!empty($obj->deleteVideosWith0Bytes)) { try { _error_log("updateFilesize: DELETE videos_id=$videos_id filename=$filename filesize=$filesize"); return $video->delete(); } catch (Exception $exc) { _error_log("updateFilesize: ERROR " . $exc->getTraceAsString()); return false; } } } if ($video->getFilesize() == $filesize) { //_error_log("updateFilesize: No need to update videos_id=$videos_id filename=$filename filesize=$filesize"); return $filesize; } $video->setFilesize($filesize); TimeLogEnd("Video::updateFilesize {$videos_id}", __LINE__); if ($video->save(false, true)) { _error_log("updateFilesize: videos_id=$videos_id filename=$filename filesize=$filesize"); return $filesize; } else { _error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize"); return false; } } public static function getAllVideosAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true) { global $global, $advancedCustom; $return = array(); $users_id = User::getId(); $get = json_encode(@$_GET); $post = json_encode(@$_POST); $md5 = md5("{$users_id}{$get}{$post}{$status}{$showOnlyLoggedUserVideos}{$ignoreGroup}" . implode("_", $videosArrayId) . "{$getStatistcs}{$showUnlisted}{$activeUsersOnly}"); $path = getCacheDir() . "getAllVideosAsync/"; make_path($path); $cacheFileName = "{$path}{$md5}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName) || filesize($cacheFileName) === 0) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getAllVideosAsync.php' '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup' '" . json_encode($videosArrayId) . "' '$getStatistcs' '$showUnlisted' '$activeUsersOnly' '{$get}' '{$post}' '{$cacheFileName}'"); _error_log("getAllVideosAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return object_to_array($return); } /** * Same as getAllVideos() method but a lighter query * @global type $global * @global type $config * @param type $showOnlyLoggedUserVideos * @return boolean */ public static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $sql = "SELECT v.* " . " FROM videos as v " . " WHERE 1=1 "; $blockedUsers = self::getBlockedUsersIdsArray(); if (!empty($blockedUsers)) { $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; } if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } - if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $sql .= " AND v.users_id = '{$user['id']}' "; } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; } if (strpos(strtolower($sql), 'limit') === false) { if (empty($global['limitForUnlimitedVideos'])) { $global['limitForUnlimitedVideos'] = empty($global['rowCount']) ? 1000 : $global['rowCount']; } if ($global['limitForUnlimitedVideos'] > 0) { $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; } } //echo $sql; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); $_GET['channelName'] = $channelName; return $return; } sqlDAL::close($res); $videos = array(); if ($res != false) { foreach ($fullData as $row) { if (empty($row['filesize'])) { $row['filesize'] = Video::updateFilesize($row['id']); } $videos[] = $row; } //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } public static function getTotalVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } if (!empty($_POST['sort']['suggested'])) { $suggestedOnly = true; } $status = str_replace("'", "", $status); $cn = ""; if (!empty($_GET['catName'])) { $cn .= ", c.clean_name as cn"; } if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})"); $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__); } } $sql = "SELECT v.users_id, v.type, v.id, v.title,v.description, c.name as category {$cn} " . "FROM videos v " . "LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 1=1 "; $blockedUsers = self::getBlockedUsersIdsArray(); if (!empty($blockedUsers)) { $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; } if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL(); } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($status == "viewable") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (is_int($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if (!empty($_GET['catName'])) { $sql .= " AND c.clean_name = '{$_GET['catName']}'"; } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } elseif ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } $sql .= AVideoPlugin::getVideoWhereClause(); - if (!empty($_POST['searchPhrase'])) { if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR"); $sql .= ")"; } else { $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description')); } } if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; } $res = sqlDAL::readSql($sql); $numRows = sqlDal::num_rows($res); sqlDAL::close($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($numRows) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getTotalVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly); $_GET['channelName'] = $channelName; return $return; } return $numRows; } public static function getTotalVideosInfo($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array()) { $obj = new stdClass(); $obj->likes = 0; $obj->disLikes = 0; $obj->views_count = 0; $obj->total_minutes = 0; $videos = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId); foreach ($videos as $value) { $obj->likes += intval($value['likes']); $obj->disLikes += intval($value['dislikes']); $obj->views_count += intval($value['views_count']); $obj->total_minutes += intval(parseDurationToSeconds($value['duration']) / 60); } return $obj; } public static function getTotalVideosInfoAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false) { global $global, $advancedCustom; $path = getCacheDir() . "getTotalVideosInfo/"; make_path($path); $cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}"; $return = array(); if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' " . " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', " . " '$getStatistcs', '$cacheFileName'"); //_error_log("getTotalVideosInfoAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public static function getViewableStatus($showUnlisted = false) { /** a = active i = inactive e = encoding x = encoding error d = downloading u = unlisted xmp4 = encoding mp4 error xwebm = encoding webm error xmp3 = encoding mp3 error xogg = encoding ogg error */ $viewable = array('a', 'xmp4', 'xwebm', 'xmp3', 'xogg'); if ($showUnlisted) { $viewable[] = "u"; } elseif (!empty($_GET['videoName'])) { $post = $_POST; if (self::isOwnerFromCleanTitle($_GET['videoName']) || Permissions::canModerateVideos()) { $viewable[] = "u"; } $_POST = $post; } return $viewable; } public static function getVideoConversionStatus($filename) { global $global; require_once $global['systemRootPath'] . 'objects/user.php'; if (!User::isLogged()) { die("Only logged users can upload"); } $object = new stdClass(); foreach (self::$types as $value) { $progressFilename = "{$global['systemRootPath']}videos/{$filename}_progress_{$value}.txt"; $content = @url_get_contents($progressFilename); $object->$value = new stdClass(); if (!empty($content)) { $object->$value = self::parseProgress($content); } else { } if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) { $video = self::getVideoFromFileName($filename); //var_dump($video, $filename); if (!empty($video)) { $object->$value->progress = self::$statusDesc[$video['status']]; } } $object->$value->filename = $progressFilename; } return $object; } private static function parseProgress($content) { //get duration of source $obj = new stdClass(); $obj->duration = 0; $obj->currentTime = 0; $obj->progress = 0; //var_dump($content);exit; preg_match("/Duration: (.*?), start:/", $content, $matches); if (!empty($matches[1])) { $rawDuration = $matches[1]; //rawDuration is in 00:00:00.00 format. This converts it to seconds. $ar = array_reverse(explode(":", $rawDuration)); $duration = floatval($ar[0]); if (!empty($ar[1])) { $duration += intval($ar[1]) * 60; } if (!empty($ar[2])) { $duration += intval($ar[2]) * 60 * 60; } //get the time in the file that is already encoded preg_match_all("/time=(.*?) bitrate/", $content, $matches); $rawTime = array_pop($matches); //this is needed if there is more than one match if (is_array($rawTime)) { $rawTime = array_pop($rawTime); } //rawTime is in 00:00:00.00 format. This converts it to seconds. $ar = array_reverse(explode(":", $rawTime)); $time = floatval($ar[0]); if (!empty($ar[1])) { $time += intval($ar[1]) * 60; } if (!empty($ar[2])) { $time += intval($ar[2]) * 60 * 60; } if (!empty($duration)) { //calculate the progress $progress = round(($time / $duration) * 100); } else { $progress = 'undefined'; } $obj->duration = $duration; $obj->currentTime = $time; $obj->progress = $progress; } return $obj; } public function delete($allowOfflineUser = false) { if (!$allowOfflineUser && !$this->userCanManageVideo()) { return false; } global $global; if (!empty($this->id)) { $this->removeNextVideos($this->id); $this->removeTrailerReference($this->id); $this->removeCampaign($this->id); $video = self::getVideoLight($this->id); $sql = "DELETE FROM videos WHERE id = ?"; } else { return false; } $resp = sqlDAL::writeSql($sql, "i", array($this->id)); if ($resp == false) { _error_log('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); return false; } else { $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); $YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); if (!empty($aws_s3)) { $aws_s3->removeFiles($video['filename']); } if (!empty($bb_b2)) { $bb_b2->removeFiles($video['filename']); } if (!empty($ftp)) { $ftp->removeFiles($video['filename']); } if (!empty($YPTStorage)) { $YPTStorage->removeFiles($video['filename'], $video['sites_id']); } $this->removeFiles($video['filename']); self::deleteThumbs($video['filename']); } return $resp; } private function removeNextVideos($videos_id) { if (!$this->userCanManageVideo()) { return false; } global $global; if (!empty($videos_id)) { $sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?"; sqlDAL::writeSql($sql, "s", array($videos_id)); } else { return false; } return true; } private function removeTrailerReference($videos_id) { if (!$this->userCanManageVideo()) { return false; } global $global; if (!empty($videos_id)) { $videoURL = self::getLink($videos_id, '', true); $sql = "UPDATE videos SET trailer1 = '' WHERE trailer1 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); $sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); $sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); } else { return false; } return true; } private function removeCampaign($videos_id) { if (ObjectYPT::isTableInstalled('vast_campaigns_has_videos')) { if (!empty($this->id)) { $sql = "DELETE FROM vast_campaigns_has_videos "; $sql .= " WHERE videos_id = ?"; $global['lastQuery'] = $sql; return sqlDAL::writeSql($sql, "i", array($videos_id)); } } return false; } private function removeFiles($filename) { if (empty($filename)) { return false; } global $global; $file = "{$global['systemRootPath']}videos/original_{$filename}"; $this->removeFilePath($file); $files = "{$global['systemRootPath']}videos/{$filename}"; $this->removeFilePath($files); } private function removeFilePath($filePath) { if (empty($filePath)) { return false; } // Streamlined for less coding space. $files = glob("{$filePath}*"); foreach ($files as $file) { if (file_exists($file)) { if (is_dir($file)) { self::rrmdir($file); } else { @unlink($file); } } } } private static function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . "/" . $object)) { self::rrmdir($dir . "/" . $object); } else { unlink($dir . "/" . $object); } } } rmdir($dir); } } public function setDescription($description) { global $global, $advancedCustom; if (empty($advancedCustom->disableHTMLDescription)) { $articleObj = AVideoPlugin::getObjectData('Articles'); require_once $global['systemRootPath'] . 'objects/ezyang/htmlpurifier/library/HTMLPurifier.auto.php'; $configPuri = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($configPuri); if (empty($articleObj->allowAttributes)) { $configPuri->set('HTML.AllowedAttributes', array('a.href', 'a.target', 'a.title', 'a.title', 'img.src', 'img.width', 'img.height')); // remove all attributes except a.href $configPuri->set('Attr.AllowedFrameTargets', array('_blank')); } if (empty($articleObj->allowAttributes)) { $configPuri->set('CSS.AllowedProperties', array()); // remove all CSS } $configPuri->set('AutoFormat.RemoveEmpty', true); // remove empty elements $pure = $purifier->purify($description); $parts = explode("", $pure); if (!empty($parts[1])) { $parts = explode("", $parts[1]); } $this->description = $parts[0]; } else { $this->description = strip_tags(br2nl($description)); } //var_dump($this->description, $description, $parts);exit; } public function setCategories_id($categories_id) { if (!Category::userCanAddInCategory($categories_id)) { return false; } // to update old cat as well when auto.. if (!empty($this->categories_id)) { $this->old_categories_id = $this->categories_id; } $this->categories_id = $categories_id; } public static function getCleanDuration($duration = "") { if (empty($duration)) { if (!empty($this) && !empty($this->duration)) { $durationParts = explode(".", $this->duration); } else { return "00:00:00"; } } else { $durationParts = explode(".", $duration); } if (empty($durationParts[0])) { return "00:00:00"; } else { $duration = $durationParts[0]; $durationParts = explode(':', $duration); if (count($durationParts) == 1) { return '0:00:' . static::addZero($durationParts[0]); } elseif (count($durationParts) == 2) { return '0:' . static::addZero($durationParts[0]) . ':' . static::addZero($durationParts[1]); } return $duration; } } private static function addZero($str) { if (intval($str) < 10) { return '0' . intval($str); } return $str; } public static function getItemPropDuration($duration = '') { $duration = static::getCleanDuration($duration); $parts = explode(':', $duration); $duration = 'PT' . intval($parts[0]) . 'H' . intval($parts[1]) . 'M' . intval($parts[2]) . 'S'; if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } return $duration; } public static function getItemDurationSeconds($duration = '') { if ($duration == "EE:EE:EE") { return 0; } $duration = static::getCleanDuration($duration); $parts = explode(':', $duration); return intval($parts[0] * 60 * 60) + intval($parts[1] * 60) + intval($parts[2]); } public static function getDurationFromFile($file) { global $global; - require_once $global['systemRootPath'] . 'objects/james-heinrich/getid3/getid3.php'; + require_once $global['systemRootPath'] . 'objects/james-heinrich/getid3/getid3/getid3.php'; // get movie duration HOURS:MM:SS.MICROSECONDS if (!file_exists($file)) { _error_log('{"status":"error", "msg":"getDurationFromFile ERROR, File (' . $file . ') Not Found"}'); return "EE:EE:EE"; } // Initialize getID3 engine $getID3 = new getID3; // Analyze file and store returned data in $ThisFileInfo $ThisFileInfo = $getID3->analyze($file); return static::getCleanDuration(@$ThisFileInfo['playtime_string']); } public static function getResolution($file) { global $videogetResolution; if (!isset($videogetResolution)) { $videogetResolution = array(); } if (isset($videogetResolution[$file])) { return $videogetResolution[$file]; } if (!file_exists($file)) { _error_log('{"status":"error", "msg":"getResolution ERROR, File (' . $file . ') Not Found"}'); $videogetResolution[$file] = 0; return 0; } if ( AVideoPlugin::isEnabledByName("Blackblaze_B2") || AVideoPlugin::isEnabledByName("AWS_S3") || AVideoPlugin::isEnabledByName("FTP_Storage") || AVideoPlugin::isEnabledByName("YPTStorage")) { $videogetResolution[$file] = 0; return 0; } global $global; if (preg_match("/.m3u8$/i", $file) && AVideoPlugin::isEnabledByName('VideoHLS') && method_exists(new VideoHLS(), 'getHLSHigestResolutionFromFile')) { $videogetResolution[$file] = VideoHLS::getHLSHigestResolutionFromFile($file); } else { require_once $global['systemRootPath'] . 'objects/james-heinrich/getid3/getid3/getid3.php'; $getID3 = new getID3; $ThisFileInfo = $getID3->analyze($file); $videogetResolution[$file] = intval(@$ThisFileInfo['video']['resolution_y']); } return $videogetResolution[$file]; } public static function getHLSDurationFromFile($file) { $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (empty($plugin)) { return 0; } return VideoHLS::getHLSDurationFromFile($file); } public function updateHLSDurationIfNeed() { $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (empty($plugin)) { return false; } return VideoHLS::updateHLSDurationIfNeed($this); } public function updateDurationIfNeed($fileExtension = ".mp4") { global $global; $source = self::getSourceFile($this->filename, $fileExtension, true); $file = $source['path']; if (!empty($this->id) && $this->duration == "EE:EE:EE" && file_exists($file)) { $this->duration = Video::getDurationFromFile($file); _error_log("Duration Updated: " . json_encode($this)); $sql = "UPDATE videos SET duration = ?, modified = now() WHERE id = ?"; $res = sqlDAL::writeSql($sql, "si", array($this->duration, $this->id)); return $this->id; } else { _error_log("Do not need update duration: " . json_encode($this)); return false; } } public function getFilename() { return $this->filename; } public function getStatus() { return $this->status; } public function getId() { return $this->id; } public function getVideoDownloadedLink() { return $this->videoDownloadedLink; } public function setVideoDownloadedLink($videoDownloadedLink) { $this->videoDownloadedLink = $videoDownloadedLink; } public static function isLandscape($pathFileName) { global $config; // get movie duration HOURS:MM:SS.MICROSECONDS if (!file_exists($pathFileName)) { echo '{"status":"error", "msg":"isLandscape ERROR, File (' . $pathFileName . ') Not Found"}'; return true; } eval('$cmd="' . $config->getExiftool() . '";'); $resp = true; // is landscape by default exec($cmd . ' 2>&1', $output, $return_val); if ($return_val !== 0) { $resp = true; } else { $w = 1; $h = 0; $rotation = 0; foreach ($output as $value) { preg_match("/Image Size.*:[^0-9]*([0-9]+x[0-9]+)/i", $value, $match); if (!empty($match)) { $parts = explode("x", $match[1]); $w = $parts[0]; $h = $parts[1]; } preg_match("/Rotation.*:[^0-9]*([0-9]+)/i", $value, $match); if (!empty($match)) { $rotation = $match[1]; } } if ($rotation == 0) { if ($w > $h) { $resp = true; } else { $resp = false; } } else { if ($w < $h) { $resp = true; } else { $resp = false; } } } //var_dump($cmd, $w, $h, $rotation, $resp);exit; return $resp; } public function userCanManageVideo() { global $advancedCustomUser; if (Permissions::canAdminVideos()) { return true; } if (empty($this->users_id) || !User::canUpload()) { return false; } // if you not admin you can only manager yours video $users_id = $this->users_id; if ($advancedCustomUser->userCanChangeVideoOwner) { $video = new Video("", "", $this->id); // query again to make sure the user is not changing the owner $users_id = $video->getUsers_id(); } if ($users_id != User::getId()) { return false; } return true; } public function getVideoGroups() { return $this->videoGroups; } public function setVideoGroups($userGroups) { if (is_array($userGroups)) { $this->videoGroups = $userGroups; } } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ public static function getTags($video_id, $type = "") { global $advancedCustom, $videos_getTags; if (empty($videos_getTags)) { $videos_getTags = array(); } $name = "{$video_id}_{$type}"; if (!empty($videos_getTags[$name])) { return $videos_getTags[$name]; } if (empty($advancedCustom->AsyncJobs)) { $videos_getTags[$name] = self::getTags_($video_id, $type); return $videos_getTags[$name]; } else { $tags = self::getTagsAsync($video_id, $type); foreach ($tags as $key => $value) { if (is_array($value)) { $tags[$key] = (object) $value; } } $videos_getTags[$name] = $tags; return $tags; } } public static function getTags_($video_id, $type = "") { global $advancedCustom, $advancedCustomUser; if (empty($advancedCustom)) { $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); } if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); } $currentPage = getCurrentPage(); $rowCount = getRowCount(); $_REQUEST['current'] = 1; $_REQUEST['rowCount'] = 1000; $video = new Video("", "", $video_id); $tags = array(); if (empty($type) || $type === "paid") { $objTag = new stdClass(); $objTag->label = __("Paid Content"); if (!empty($advancedCustom->paidOnlyShowLabels)) { if (!empty($video->getOnly_for_paid())) { $objTag->type = "warning"; $objTag->text = $advancedCustom->paidOnlyLabel; } else { $objTag->type = "success"; $objTag->text = $advancedCustom->paidOnlyFreeLabel; } } else { $ppv = AVideoPlugin::getObjectDataIfEnabled("PayPerView"); if ($advancedCustomUser->userCanProtectVideosWithPassword && !empty($video->getVideo_password())) { $objTag->type = "danger"; $objTag->text = ''; } elseif (!empty($video->getOnly_for_paid())) { $objTag->type = "warning"; $objTag->text = $advancedCustom->paidOnlyLabel; } elseif ($ppv && PayPerView::isVideoPayPerView($video_id)) { if (!empty($ppv->showPPVLabel)) { $objTag->type = "warning"; $objTag->text = "PPV"; } else { $objTag->type = "warning"; $objTag->text = __("Private"); } } elseif (!Video::isPublic($video_id)) { $objTag->type = "warning"; $objTag->text = __("Private"); } else { $objTag->type = "success"; $objTag->text = $advancedCustom->paidOnlyFreeLabel; } } $tags[] = $objTag; $objTag = new stdClass(); } /** a = active i = inactive e = encoding x = encoding error d = downloading u = unlisted xmp4 = encoding mp4 error xwebm = encoding webm error xmp3 = encoding mp3 error xogg = encoding ogg error ximg = get image error */ if (empty($type) || $type === "status") { $objTag = new stdClass(); $objTag->label = __("Status"); switch ($video->getStatus()) { case 'a': $objTag->type = "success"; $objTag->text = __("Active"); break; case 'i': $objTag->type = "warning"; $objTag->text = __("Inactive"); break; case 'e': $objTag->type = "info"; $objTag->text = __("Encoding"); break; case 'd': $objTag->type = "info"; $objTag->text = __("Downloading"); break; case 'u': $objTag->type = "info"; $objTag->text = __("Unlisted"); break; case 'xmp4': $objTag->type = "danger"; $objTag->text = __("Encoding mp4 error"); break; case 'xwebm': $objTag->type = "danger"; $objTag->text = __("Encoding xwebm error"); break; case 'xmp3': $objTag->type = "danger"; $objTag->text = __("Encoding xmp3 error"); break; case 'xogg': $objTag->type = "danger"; $objTag->text = __("Encoding xogg error"); break; case 'ximg': $objTag->type = "danger"; $objTag->text = __("Get imgage error"); break; default: $objTag->type = "danger"; $objTag->text = __("Status not found"); break; } $objTag->text = $objTag->text; $tags[] = $objTag; $objTag = new stdClass(); } if (empty($type) || $type === "userGroups") { $groups = UserGroups::getVideoGroups($video_id); $objTag = new stdClass(); $objTag->label = __("Group"); if (empty($groups)) { $status = $video->getStatus(); if ($status == 'u') { $objTag->type = "info"; $objTag->text = __("Unlisted"); $tags[] = $objTag; $objTag = new stdClass(); } else { //$objTag->type = "success"; //$objTag->text = __("Public"); } } else { foreach ($groups as $value) { $objTag = new stdClass(); $objTag->label = __("Group"); $objTag->type = "info"; $objTag->text = "{$value['group_name']}"; $tags[] = $objTag; $objTag = new stdClass(); } } } if (empty($type) || $type === "category") { require_once 'category.php'; $sort = null; if (!empty($_POST['sort']['title'])) { $sort = $_POST['sort']; unset($_POST['sort']); } $category = Category::getCategory($video->getCategories_id()); if (!empty($sort)) { $_POST['sort'] = $sort; } $objTag = new stdClass(); $objTag->label = __("Category"); if (!empty($category)) { $objTag->type = "default"; $objTag->text = $category['name']; $tags[] = $objTag; $objTag = new stdClass(); } } if (empty($type) || $type === "source") { $url = $video->getVideoDownloadedLink(); $parse = parse_url($url); $objTag = new stdClass(); $objTag->label = __("Source"); if (!empty($parse['host'])) { $objTag->type = "danger"; $objTag->text = $parse['host']; $tags[] = $objTag; $objTag = new stdClass(); } else { $objTag->type = "info"; $objTag->text = __("Local File"); $tags[] = $objTag; $objTag = new stdClass(); } } $array2 = AVideoPlugin::getVideoTags($video_id); if (is_array($array2)) { $tags = array_merge($tags, $array2); } //var_dump($tags); $_REQUEST['current'] = $currentPage; $_REQUEST['rowCount'] = $rowCount; return $tags; } public static function deleteTagsAsync($video_id) { global $global; if (empty($video_id)) { return false; } $name = "getVideoTags{$video_id}"; ObjectYPT::deleteCache($name); _session_start(); unset($_SESSION['getVideoTags'][$video_id]); $path = getCacheDir() . "getTagsAsync/"; if (!is_dir($path)) { return false; } $cacheFileName = "{$path}_{$video_id}_"; $files = glob("{$cacheFileName}*"); foreach ($files as $file) { unlink($file); } } public static function getTagsAsync($video_id, $type = "video") { global $global, $advancedCustom; $path = getCacheDir() . "getTagsAsync/"; make_path($path); $cacheFileName = "{$path}_{$video_id}_{$type}"; $return = array(); if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getTags_($video_id, $type); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 300) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTags.php' '$video_id' '$type' '{$cacheFileName}'"); //_error_log("getTags: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return (array) $return; } public function getCategories_id() { return $this->categories_id; } public function getType() { return $this->type; } public static function fixCleanTitle($clean_title, $count, $videoId, $original_title = "") { global $global; if (empty($original_title)) { $original_title = $clean_title; } $sql = "SELECT * FROM videos WHERE clean_title = '{$clean_title}' "; if (!empty($videoId)) { $sql .= " AND id != {$videoId} "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $cleanTitleExists = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($cleanTitleExists != false) { return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $videoId, $original_title); } return $clean_title; } /** * * @global type $global * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ public static function isOwner($videos_id, $users_id = 0) { global $global; if (empty($users_id)) { $users_id = User::getId(); if (empty($users_id)) { return false; } } $video_owner = self::getOwner($videos_id); if ($video_owner) { if ($video_owner == $users_id) { return true; } } return false; } public static function isOwnerFromCleanTitle($clean_title, $users_id = 0) { global $global; $video = self::getVideoFromCleanTitle($clean_title); return self::isOwner($video['id'], $users_id); } /** * * @global type $global * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ public static function getOwner($videos_id) { global $global; $sql = "SELECT users_id FROM videos WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { if ($videoRow != false) { return $videoRow['users_id']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } /** * * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ public static function canEdit($videos_id, $users_id = 0) { if (empty($videos_id)) { return false; } if (empty($users_id)) { $users_id = User::getId(); if (empty($users_id)) { return false; } } $user = new User($users_id); if (empty($user)) { return false; } if ($user->getIsAdmin()) { return true; } if (Permissions::canAdminVideos()) { return true; } return self::isOwner($videos_id, $users_id); } public static function getRandom($excludeVideoId = false) { return static::getVideo("", "viewable", false, $excludeVideoId); } public static function getVideoQueryFileter() { global $global; $sql = ""; if (!empty($_GET['playlist_id'])) { require_once $global['systemRootPath'] . 'objects/playlist.php'; $ids = PlayList::getVideosIdFromPlaylist($_GET['playlist_id']); if (!empty($ids)) { $sql .= " AND v.id IN (" . implode(",", $ids) . ") "; } } return $sql; } public function getTitle() { return $this->title; } public function getClean_title() { return $this->clean_title; } public function getDescription() { return $this->description; } public function getExistingVideoFile() { $source = self::getHigestResolutionVideoMP4Source($this->getFilename(), true); $size = filesize($source['path']); if ($size <= 20) {// it is a dummy file $url = $source['url']; $filename = getTmpDir("getExistingVideoFile") . md5($url); wget($url, $filename); return $filename; } return $source['path']; } public function getTrailer1() { return $this->trailer1; } public function getTrailer2() { return $this->trailer2; } public function getTrailer3() { return $this->trailer3; } public function getRate() { return $this->rate; } public function setTrailer1($trailer1) { if (filter_var($trailer1, FILTER_VALIDATE_URL)) { $this->trailer1 = $trailer1; } else { $this->trailer1 = ""; } } public function setTrailer2($trailer2) { if (filter_var($trailer2, FILTER_VALIDATE_URL)) { $this->trailer2 = $trailer2; } else { $this->trailer2 = ""; } } public function setTrailer3($trailer3) { if (filter_var($trailer3, FILTER_VALIDATE_URL)) { $this->trailer3 = $trailer3; } else { $this->trailer3 = ""; } } public function setRate($rate) { $this->rate = floatval($rate); } public function getYoutubeId() { return $this->youtubeId; } public function setYoutubeId($youtubeId) { $this->youtubeId = $youtubeId; } public function setTitle($title) { if ($title === "Video automatically booked" && !empty($this->title)) { return false; } $this->title = strip_tags($title); if (strlen($this->title) > 190) { $this->title = substr($this->title, 0, 187) . '...'; } } public function setFilename($filename, $force = false) { if ($force || empty($this->filename)) { $this->filename = $filename; } return $this->filename; } public function getNext_videos_id() { return $this->next_videos_id; } public function setNext_videos_id($next_videos_id) { $this->next_videos_id = $next_videos_id; } public function queue($types = array()) { global $config; if (!User::canUpload()) { return false; } global $global; $obj = new stdClass(); $obj->error = true; $target = $config->getEncoderURL() . "queue"; $postFields = array( 'user' => User::getUserName(), 'pass' => User::getUserPass(), 'fileURI' => $global['webSiteRootURL'] . "videos/original_{$this->getFilename()}", 'filename' => $this->getFilename(), 'videos_id' => $this->getId(), "notifyURL" => "{$global['webSiteRootURL']}" ); if (empty($types) && AVideoPlugin::isEnabledByName("VideoHLS")) { $postFields['inputHLS'] = 1; } elseif (!empty($types)) { foreach ($types as $key => $value) { $postFields[$key] = $value; } } _error_log("SEND To QUEUE: ($target) " . json_encode($postFields)); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $target); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); $r = curl_exec($curl); $obj->response = $r; if ($errno = curl_errno($curl)) { $error_message = curl_strerror($errno); //echo "cURL error ({$errno}):\n {$error_message}"; $obj->msg = "cURL error ({$errno}):\n {$error_message}"; } else { $obj->error = false; } _error_log("QUEUE CURL: ($target) " . json_encode($obj)); curl_close($curl); return $obj; } public function getVideoLink() { return $this->videoLink; } public function setVideoLink($videoLink) { $this->videoLink = $videoLink; } public function getCan_download() { return $this->can_download; } public function getCan_share() { return $this->can_share; } public function setCan_download($can_download) { $this->can_download = (empty($can_download) || $can_download === "false") ? 0 : 1; } public function setCan_share($can_share) { $this->can_share = (empty($can_share) || $can_share === "false") ? 0 : 1; } public function getOnly_for_paid() { return $this->only_for_paid; } public function setOnly_for_paid($only_for_paid) { $this->only_for_paid = (empty($only_for_paid) || $only_for_paid === "false") ? 0 : 1; } /** * * @param type $filename * @param type $type * @return type .jpg .gif .webp _thumbs.jpg _Low.mp4 _SD.mp4 _HD.mp4 */ public static function getSourceFile($filename, $type = ".jpg", $includeS3 = false) { global $global, $advancedCustom, $videosPaths, $VideoGetSourceFile; //if(!isValidFormats($type)){ //return array(); //} $cacheName = md5($filename . $type . $includeS3); if (isset($VideoGetSourceFile[$cacheName])) { if (!preg_match("/token=/", $VideoGetSourceFile[$cacheName]['url'])) { return $VideoGetSourceFile[$cacheName]; } } - // check if there is a webp image if ($type === '.gif' && (empty($_SERVER['HTTP_USER_AGENT']) || get_browser_name($_SERVER['HTTP_USER_AGENT']) !== 'Safari')) { $path = "{$global['systemRootPath']}videos/{$filename}.webp"; if (file_exists($path)) { $type = ".webp"; } } if (empty($videosPaths[$filename][$type][intval($includeS3)])) { $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); if (!empty($aws_s3)) { $aws_s3_obj = $aws_s3->getDataObject(); if (!empty($aws_s3_obj->useS3DirectLink)) { $includeS3 = true; } } elseif (!empty($bb_b2)) { $bb_b2_obj = $bb_b2->getDataObject(); if (!empty($bb_b2_obj->useDirectLink)) { $includeS3 = true; } } elseif (!empty($ftp)) { $includeS3 = true; } $token = ""; $secure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); if ((preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip")) { $vars = array(); if (!empty($secure)) { $vars[] = $secure->getToken($filename); } if (!empty($vars)) { $token = "?" . implode("&", $vars); } } $source = array(); $source['path'] = "{$global['systemRootPath']}videos/{$filename}{$type}"; if ($type == ".m3u8") { $source['path'] = "{$global['systemRootPath']}videos/{$filename}/index{$type}"; } $cleanFileName = self::getCleanFilenameFromFile($filename); $video = Video::getVideoFromFileNameLight($cleanFileName); if (empty($video)) { _error_log("Video::getSourceFile($filename, $type, $includeS3) ERROR video not found ($cleanFileName)"); $VideoGetSourceFile[$cacheName] = false; return false; } $canUseCDN = canUseCDN($video['id']); if (!empty($video['sites_id']) && (preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip") && @filesize($source['path']) < 20) { $site = new Sites($video['sites_id']); $siteURL = rtrim($site->getUrl(), '/') . '/'; $source['url'] = "{$siteURL}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}"; } } elseif (!empty($advancedCustom->videosCDN) && $canUseCDN) { $advancedCustom->videosCDN = rtrim($advancedCustom->videosCDN, '/') . '/'; $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}"; } } else { $source['url'] = "{$global['webSiteRootURL']}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; } } /* need it because getDurationFromFile */ if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf" || $type == ".zip")) { if (file_exists($source['path']) && filesize($source['path']) < 1024) { if (!empty($aws_s3)) { $source = $aws_s3->getAddress("{$filename}{$type}"); } elseif (!empty($bb_b2)) { $source = $bb_b2->getAddress("{$filename}{$type}"); } elseif (!empty($ftp)) { $source = $ftp->getAddress("{$filename}{$type}"); } } } if (!file_exists($source['path']) || ($type !== ".m3u8" && !is_dir($source['path']) && (filesize($source['path']) < 1000 && filesize($source['path']) != 10))) { if ($type != "_thumbsV2.jpg" && $type != "_thumbsSmallV2.jpg" && $type != "_portrait_thumbsV2.jpg" && $type != "_portrait_thumbsSmallV2.jpg") { $VideoGetSourceFile[$cacheName] = array('path' => false, 'url' => false); return $VideoGetSourceFile[$cacheName]; } } $videosPaths[$filename][$type][intval($includeS3)] = $source; } else { $source = $videosPaths[$filename][$type][intval($includeS3)]; } if (substr($type, -4) === ".jpg" || substr($type, -4) === ".png" || substr($type, -4) === ".gif" || substr($type, -4) === ".webp") { $x = uniqid(); if (file_exists($source['path'])) { $x = filemtime($source['path']); } elseif (!empty($video)) { $x = strtotime($video['modified']); } $source['url'] .= "?{$x}"; } //ObjectYPT::setCache($name, $source); $VideoGetSourceFile[$cacheName] = $source; return $VideoGetSourceFile[$cacheName]; } public static function getCleanFilenameFromFile($filename) { if (empty($filename)) { return ""; } $cleanName = str_replace( array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku', '_2160', '_1440', '_1080', '_720', '_480', '_360', '_240', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2'), array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''), $filename ); $path_parts = pathinfo($cleanName); if (!empty($path_parts["extension"]) && $path_parts["extension"] === "m3u8") { preg_match('/videos\/([^\/]+)/', $path_parts["dirname"], $matches); if (!empty($matches[1])) { $path_parts['filename'] = $matches[1]; } } if (empty($path_parts['extension'])) { //_error_log("Video::getCleanFilenameFromFile could not find extension of ".$filename); if (!empty($path_parts['filename'])) { return $path_parts['filename']; } else { return $filename; } } elseif (strlen($path_parts['extension']) > 4) { return $cleanName; } else { return $path_parts['filename']; } } public static function getSpecificResolution($filename, $desired_resolution) { $filename = self::getCleanFilenameFromFile($filename); $cacheName = "getSpecificResolution($filename)"; $return = ObjectYPT::getCache($cacheName, 0); if (!empty($return)) { return object_to_array($return); } $name0 = "Video:::getSpecificResolution($filename)"; TimeLogStart($name0); $name1 = "Video:::getSpecificResolution::getVideosURL_V2($filename)"; TimeLogStart($name1); $sources = getVideosURL_V2($filename); if (!is_array($sources)) { _error_log("Video:::getSpecificResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources)); return array(); } TimeLogEnd($name1, __LINE__); $return = array(); foreach ($sources as $key => $value) { if ($value['type'] === 'video') { $parts = explode("_", $key); $resolution = intval(@$parts[1]); if (empty($resolution)) { $name2 = "Video:::getSpecificResolution::getResolution({$value["path"]})"; TimeLogStart($name2); $resolution = self::getResolution($value["path"]); TimeLogEnd($name2, __LINE__); } if (!isset($return['resolution']) || $resolution == $desired_resolution) { $return = $value; $return['resolution'] = $resolution; $return['resolution_text'] = getResolutionText($return['resolution']); $return['resolution_label'] = getResolutionLabel($return['resolution']); $return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}"); } } } TimeLogEnd($name0, __LINE__); ObjectYPT::setCache($cacheName, $return); return $return; } public static function getHigestResolution($filename) { $filename = self::getCleanFilenameFromFile($filename); $cacheName = "getHigestResolution($filename)"; $return = ObjectYPT::getCache($cacheName, 0); if (!empty($return)) { return object_to_array($return); } $name0 = "Video:::getHigestResolution($filename)"; TimeLogStart($name0); $name1 = "Video:::getHigestResolution::getVideosURL_V2($filename)"; TimeLogStart($name1); $sources = getVideosURL_V2($filename); if (!is_array($sources)) { _error_log("Video:::getHigestResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources)); return array(); } TimeLogEnd($name1, __LINE__); $return = array(); foreach ($sources as $key => $value) { if ($value['type'] === 'video') { $parts = explode("_", $key); $resolution = intval(@$parts[1]); if (empty($resolution)) { $name2 = "Video:::getHigestResolution::getResolution({$value["path"]})"; TimeLogStart($name2); $resolution = self::getResolution($value["path"]); TimeLogEnd($name2, __LINE__); } if (!isset($return['resolution']) || $resolution > $return['resolution']) { $return = $value; $return['resolution'] = $resolution; $return['resolution_text'] = getResolutionText($return['resolution']); $return['resolution_label'] = getResolutionLabel($return['resolution']); $return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}"); } } } TimeLogEnd($name0, __LINE__); ObjectYPT::setCache($cacheName, $return); return $return; } public static function getResolutionFromFilename($filename) { $resolution = false; if (preg_match("/_([0-9]+).(mp4|webm)/i", $filename, $matches)) { if (!empty($matches[1])) { $resolution = intval($matches[1]); } } elseif (preg_match('/res([0-9]+)\/index.m3u8/i', $filename, $matches)) { if (!empty($matches[1])) { $resolution = intval($matches[1]); } } //var_dump($filename, $resolution);exit; return $resolution; } public static function getHigestResolutionVideoMP4Source($filename, $includeS3 = false) { $types = array('', '_HD', '_SD', '_Low'); foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".mp4", $includeS3); if (!empty($source['url'])) { return $source; } } return false; } public static function getHigherVideoPathFromID($videos_id) { if (empty($videos_id)) { return false; } $paths = self::getVideosPathsFromID($videos_id); $types = array(0, 2160, 1330, 1080, 720, 'HD', 'SD', 'Low', 480, 360, 240); if (!empty($paths['mp4'])) { foreach ($types as $value) { if (!empty($paths['mp4'][$value])) { if (is_string($paths['mp4'][$value])) { return $paths['mp4'][$value]; } else { return $paths['mp4'][$value]["url"]; } } } } if (!empty($paths['webm'])) { foreach ($types as $value) { if (!empty($paths['webm'][$value])) { if (is_string($paths['webm'][$value])) { return $paths['webm'][$value]; } else { return $paths['webm'][$value]["url"]; } } } } if (!empty($paths['m3u8'])) { if (!empty($paths['m3u8'])) { if (is_string($paths['m3u8']["url"])) { return $paths['m3u8']["url"]; } elseif (is_string($paths['m3u8'][$value])) { return $paths['m3u8'][$value]; } else { return $paths['m3u8'][$value]["url"]; } } } if (!empty($paths['mp3'])) { return $paths['mp3']; } return false; } public static function getVideosPathsFromID($videos_id) { if (empty($videos_id)) { return false; } $video = new Video("", "", $videos_id); return self::getVideosPaths($video->getFilename(), true); } public static function getVideosPaths($filename, $includeS3 = false) { $types = array('', '_Low', '_SD', '_HD', '_2160', '_1440', '_1080', '_720', '_480', '_360', '_240'); $videos = array(); $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (!empty($plugin)) { $videos = VideoHLS::getSourceFile($filename, $includeS3); } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".mp4", $includeS3); if (!empty($source['url'])) { $videos['mp4'][str_replace("_", "", $value)] = $source['url']; } } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".webm", $includeS3); if (!empty($source['url'])) { $videos['webm'][str_replace("_", "", $value)] = $source['url']; } } $source = self::getSourceFile($filename, ".pdf", $includeS3); if (!empty($source['url'])) { $videos['pdf'] = $source['url']; } $source = self::getSourceFile($filename, ".zip", $includeS3); if (!empty($source['url'])) { $videos['zip'] = $source['url']; } $source = self::getSourceFile($filename, ".mp3", $includeS3); if (!empty($source['url'])) { $videos['mp3'] = $source['url']; } return $videos; } public static function getStoragePath() { global $global; $path = "{$global['systemRootPath']}videos/"; return $path; } public static function getImageFromFilename($filename, $type = "video", $async = false) { global $advancedCustom; // I dont know why but I had to remove it to avoid ERR_RESPONSE_HEADERS_TOO_BIG header_remove('Set-Cookie'); if (empty($advancedCustom->AsyncJobs) && !$async) { return self::getImageFromFilename_($filename, $type); } else { return self::getImageFromFilenameAsync($filename, $type); } } public static function getPoster($videos_id) { $images = self::getImageFromID($videos_id); if (!empty($images->poster)) { return $images->poster; } if (!empty($images->posterPortrait)) { return $images->poster; } return false; } public static function getRokuImage($videos_id) { global $global; $images = self::getImageFromID($videos_id); $imagePath = $images->posterLandscapePath; if (empty($imagePath) || !file_exists($imagePath)) { $imagePath = $images->posterLandscapeThumbs; } if (empty($imagePath) || !file_exists($imagePath)) { $imagePath = $images->poster; } $rokuImage = str_replace(".jpg", "_roku.jpg", $imagePath); if (convertImageToRoku($images->posterLandscapePath, $rokuImage)) { return str_replace($global['systemRootPath'], $global['webSiteRootURL'], $rokuImage); } return "{$global['webSiteRootURL']}view/img/notfound.jpg"; } public static function clearImageCache($filename, $type = "video") { $cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : ""); return ObjectYPT::deleteCache($cacheFileName); } public static function getImageFromFilename_($filename, $type = "video") { if (empty($filename)) { return array(); } global $_getImageFromFilename_; if (empty($_getImageFromFilename_)) { $_getImageFromFilename_ = array(); } $cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : ""); if (!empty($_getImageFromFilename_[$cacheFileName])) { $obj = $_getImageFromFilename_[$cacheFileName]; } else { $cache = ObjectYPT::getCache($cacheFileName, 0); if (!empty($cache)) { return $cache; } global $global, $advancedCustom; /* $name = "getImageFromFilename_{$filename}{$type}_"; $cached = ObjectYPT::getCache($name, 86400);//one day if(!empty($cached)){ return $cached; } * */ $obj = new stdClass(); $gifSource = self::getSourceFile($filename, ".gif"); $gifPortraitSource = self::getSourceFile($filename, "_portrait.gif"); $jpegSource = self::getSourceFile($filename, ".jpg"); $jpegPortraitSource = self::getSourceFile($filename, "_portrait.jpg"); $jpegPortraitThumbs = self::getSourceFile($filename, "_portrait_thumbsV2.jpg"); $jpegPortraitThumbsSmall = self::getSourceFile($filename, "_portrait_thumbsSmallV2.jpg"); $thumbsSource = self::getSourceFile($filename, "_thumbsV2.jpg"); $thumbsSmallSource = self::getSourceFile($filename, "_thumbsSmallV2.jpg"); if (empty($jpegSource)) { return array(); } $obj->poster = $jpegSource['url']; $obj->posterPortrait = $jpegPortraitSource['url']; $obj->posterPortraitPath = $jpegPortraitSource['path']; $obj->posterPortraitThumbs = $jpegPortraitThumbs['url']; $obj->posterPortraitThumbsSmall = $jpegPortraitThumbsSmall['url']; $obj->thumbsGif = $gifSource['url']; $obj->gifPortrait = $gifPortraitSource['url']; $obj->thumbsJpg = $thumbsSource['url']; $obj->thumbsJpgSmall = $thumbsSmallSource['url']; $obj->posterLandscape = $jpegSource['url']; $obj->posterLandscapePath = $jpegSource['path']; $obj->posterLandscapeThumbs = $thumbsSource['url']; $obj->posterLandscapeThumbsSmall = $thumbsSmallSource['url']; if (file_exists($gifSource['path'])) { $obj->thumbsGif = $gifSource['url']; } if (file_exists($jpegPortraitSource['path'])) { // create thumbs if (!file_exists($jpegPortraitThumbs['path']) && filesize($jpegPortraitSource['path']) > 1024) { _error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbs['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait); } else { im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait); } } // create thumbs if (!file_exists($jpegPortraitThumbsSmall['path']) && filesize($jpegPortraitSource['path']) > 1024) { _error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbsSmall['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait); } else { im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait, 5); } } } else { if ($type == "article") { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/article_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/article_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/article_portrait.png"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/article_portrait.png"; } elseif ($type == "pdf") { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/pdf_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/pdf_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/pdf_portrait.png"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/pdf_portrait.png"; } /* else if ($type == "image") { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/image_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/image_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/image_portrait.png"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/image_portrait.png"; } */ elseif ($type == "zip") { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/zip_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/zip_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/zip_portrait.png"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/zip_portrait.png"; } else { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/notfound_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg"; } } if (file_exists($jpegSource['path'])) { $obj->poster = $jpegSource['url']; $obj->thumbsJpg = $thumbsSource['url']; // create thumbs if (!file_exists($thumbsSource['path']) && filesize($jpegSource['path']) > 1024) { _error_log("Resize JPG {$jpegSource['path']}, {$thumbsSource['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); } else { im_resizeV2($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); } } // create thumbs if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) { _error_log("Resize Small JPG {$jpegSource['path']}, {$thumbsSmallSource['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); } else { im_resizeV2($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape, 5); } } } else { if ($type == "article") { $obj->poster = "{$global['webSiteRootURL']}view/img/article.png"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/article.png"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/article.png"; } elseif ($type == "pdf") { $obj->poster = "{$global['webSiteRootURL']}view/img/pdf.png"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/pdf.png"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/pdf.png"; } elseif ($type == "image") { $obj->poster = "{$global['webSiteRootURL']}view/img/image.png"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/image.png"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/image.png"; } elseif ($type == "zip") { $obj->poster = "{$global['webSiteRootURL']}view/img/zip.png"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/zip.png"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/zip.png"; } elseif (($type !== "audio") && ($type !== "linkAudio")) { $obj->poster = "{$global['webSiteRootURL']}view/img/notfound.jpg"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/notfoundThumbs.jpg"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/notfoundThumbsSmall.jpg"; } else { $obj->poster = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/audio_waveThumbs.jpg"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/audio_waveThumbsSmall.jpg"; } } if (empty($obj->thumbsJpg)) { $obj->thumbsJpg = $obj->poster; } if (empty($obj->thumbsJpgSmall)) { $obj->thumbsJpgSmall = $obj->poster; } //ObjectYPT::setCache($name, $obj); if (!empty($advancedCustom->disableAnimatedGif)) { $obj->thumbsGif = false; } ObjectYPT::setCache($cacheFileName, $obj); $_getImageFromFilename_[$cacheFileName] = $obj; } return $obj; } public static function getImageFromFilenameAsync($filename, $type = "video") { global $global, $advancedCustom; $return = array(); $path = getCacheDir() . "getImageFromFilenameAsync/"; make_path($path); $cacheFileName = "{$path}_{$filename}_{$type}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getImageFromFilename_($filename, $type); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getImageFromFilenameAsync.php' '$filename' '$type' '{$cacheFileName}'"); //_error_log("getImageFromFilenameAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public static function getImageFromID($videos_id, $type = "video") { $video = new Video("", "", $videos_id); return self::getImageFromFilename($video->getFilename()); } public function getViews_count() { return intval($this->views_count); } public static function get_clean_title($videos_id) { global $global; $sql = "SELECT * FROM videos WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { if ($videoRow != false) { return $videoRow['clean_title']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } public static function get_id_from_clean_title($clean_title) { global $global; $sql = "SELECT * FROM videos WHERE clean_title = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($clean_title)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { if ($videoRow != false) { return $videoRow['id']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } public function getChannelName() { return User::_getChannelName($this->getUsers_id()); } public function getChannelLink() { return User::getChannelLink($this->getUsers_id()); } /** * * @global type $global * @param type $videos_id * @param type $clean_title * @param type $embed * @param type $type URLFriendly or permalink * @return String a web link */ public static function getLinkToVideo($videos_id, $clean_title = "", $embed = false, $type = "URLFriendly", $get = array()) { if (!empty($_GET['evideo'])) { $v = self::decodeEvideo(); if (!empty($v['video']['videoLink'])) { if ($embed) { return parseVideos($v['video']['videoLink']); } else { return $v['video']['videoLink']; } } } global $global, $advancedCustomUser, $advancedCustom; if (empty($videos_id) && !empty($clean_title)) { $videos_id = self::get_id_from_clean_title($clean_title); } $video = new Video("", "", $videos_id); if ($advancedCustomUser->addChannelNameOnLinks) { $get['channelName'] = $video->getChannelName(); } unset($get['v']); unset($get['videoName']); unset($get['videoName']); unset($get['isMediaPlaySite']); unset($get['parentsOnly']); $get_http = http_build_query($get); if (empty($get_http)) { $get_http = ""; } else { $get_http = "?{$get_http}"; } if ($type == "URLFriendly") { $cat = ""; if (!empty($_GET['catName'])) { $cat = "cat/{$_GET['catName']}/"; } if (empty($clean_title)) { $clean_title = $video->getClean_title(); } $clean_title = urlencode($clean_title); $subDir = "video"; $subEmbedDir = "videoEmbed"; if ($video->getType() == 'article') { $subDir = "article"; $subEmbedDir = "articleEmbed"; } if ($embed) { if (empty($advancedCustom->useVideoIDOnSEOLinks)) { return "{$global['webSiteRootURL']}{$subEmbedDir}/{$clean_title}{$get_http}"; } else { return "{$global['webSiteRootURL']}{$subEmbedDir}/{$videos_id}/{$clean_title}{$get_http}"; } } else { if (empty($advancedCustom->useVideoIDOnSEOLinks)) { return "{$global['webSiteRootURL']}{$cat}{$subDir}/{$clean_title}{$get_http}"; } else { return "{$global['webSiteRootURL']}{$subDir}/{$videos_id}/{$clean_title}{$get_http}"; } } } else { if ($embed) { return "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}"; } else { return "{$global['webSiteRootURL']}v/{$videos_id}{$get_http}"; } } } public static function getPermaLink($videos_id, $embed = false, $get = array()) { return self::getLinkToVideo($videos_id, "", $embed, "permalink", $get); } public static function getURLFriendly($videos_id, $embed = false, $get = array()) { return self::getLinkToVideo($videos_id, "", $embed, "URLFriendly", $get); } public static function getPermaLinkFromCleanTitle($clean_title, $embed = false, $get = array()) { return self::getLinkToVideo("", $clean_title, $embed, "permalink", $get); } public static function getURLFriendlyFromCleanTitle($clean_title, $embed = false, $get = array()) { return self::getLinkToVideo("", $clean_title, $embed, "URLFriendly", $get); } public static function getLink($videos_id, $clean_title, $embed = false, $get = array()) { global $advancedCustom; if (!empty($advancedCustom->usePermalinks)) { $type = "permalink"; } else { $type = "URLFriendly"; } return self::getLinkToVideo($videos_id, $clean_title, $embed, $type, $get); } public static function getTotalVideosThumbsUpFromUser($users_id, $startDate, $endDate) { global $global; $sql = "SELECT id from videos WHERE users_id = ? "; $res = sqlDAL::readSql($sql, "i", array($users_id)); $videoRows = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $r = array('thumbsUp' => 0, 'thumbsDown' => 0); if ($res != false) { foreach ($videoRows as $row) { $values = array($row['id']); $format = "i"; $sql = "SELECT id from likes WHERE videos_id = ? AND `like` = 1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsUp'] += $countRow; $format = ""; $values = array(); $sql = "SELECT id from likes WHERE videos_id = {$row['id']} AND `like` = -1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsDown'] += $countRow; } } return $r; } public static function deleteThumbs($filename, $doNotDeleteSprit = false) { if (empty($filename)) { return false; } global $global; $filePath = "{$global['systemRootPath']}videos/{$filename}"; // Streamlined for less coding space. $files = glob("{$filePath}*_thumbs*.jpg"); foreach ($files as $file) { if (file_exists($file)) { if ($doNotDeleteSprit && strpos($file, '_thumbsSprit.jpg') !== false) { continue; } @unlink($file); } } ObjectYPT::deleteCache($filename); ObjectYPT::deleteCache($filename . "article"); ObjectYPT::deleteCache($filename . "pdf"); ObjectYPT::deleteCache($filename . "video"); Video::clearImageCache($filename); Video::clearImageCache($filename, "article"); Video::clearImageCache($filename, "pdf"); Video::clearImageCache($filename, "audio"); clearVideosURL($filename); return true; } public static function clearCache($videos_id) { _error_log("Video:clearCache($videos_id)"); $video = new Video("", "", $videos_id); $filename = $video->getFilename(); if (empty($filename)) { _error_log("Video:clearCache filename not found"); return false; } self::deleteThumbs($filename, true); ObjectYPT::deleteCache("otherInfo{$videos_id}"); ObjectYPT::deleteCache($filename); ObjectYPT::deleteCache("getVideosURL_V2$filename"); ObjectYPT::deleteCache($filename . "article"); ObjectYPT::deleteCache($filename . "pdf"); ObjectYPT::deleteCache($filename . "video"); Video::clearImageCache($filename); Video::clearImageCache($filename, "article"); Video::clearImageCache($filename, "pdf"); Video::clearImageCache($filename, "audio"); Video::deleteTagsAsync($videos_id); clearVideosURL($filename); AVideoPlugin::deleteVideoTags($videos_id); ObjectYPT::setLastDeleteALLCacheTime(); return true; } public static function clearCacheFromFilename($fileName) { _error_log("Video:clearCacheFromFilename($fileName)"); $video = self::getVideoFromFileNameLight($fileName); if (empty($video['id'])) { return false; } return self::clearCache($video['id']); } public static function getVideoPogress($videos_id, $users_id = 0) { if (empty($users_id)) { if (!User::isLogged()) { return 0; } $users_id = User::getId(); } return VideoStatistic::getLastVideoTimeFromVideo($videos_id, $users_id); } public static function getVideoPogressPercent($videos_id, $users_id = 0) { $lastVideoTime = self::getVideoPogress($videos_id, $users_id); if (empty($lastVideoTime)) { return array('percent' => 0, 'lastVideoTime' => 0); } // start incremental search and save $sql = "SELECT duration FROM `videos` WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (empty($row) || empty($row['duration'])) { return array('percent' => 0, 'lastVideoTime' => 0); } $duration = parseDurationToSeconds($row['duration']); if (empty($duration)) { return array('percent' => 0, 'lastVideoTime' => 0); } if ($lastVideoTime > $duration) { return array('percent' => 100, 'lastVideoTime' => $lastVideoTime); } return array('percent' => ($lastVideoTime / $duration) * 100, 'lastVideoTime' => $lastVideoTime); } public function getRrating() { return $this->rrating; } public function setRrating($rrating) { $rrating = strtolower($rrating); if (!in_array($rrating, self::$rratingOptions)) { $rrating = ''; } $this->rrating = $rrating; } public static function getVideoType($filename) { global $_getVideoType; if (!isset($_getVideoType)) { $_getVideoType = array(); } if (isset($_getVideoType[$filename])) { return $_getVideoType[$filename]; } $obj = new stdClass(); $paths = self::getVideosPaths($filename); $obj->mp4 = !empty($paths['mp4']) ? true : false; $obj->webm = !empty($paths['webm']) ? true : false; $obj->m3u8 = !empty($paths['m3u8']) ? true : false; $obj->pdf = !empty($paths['pdf']) ? true : false; $obj->mp3 = !empty($paths['mp3']) ? true : false; $_getVideoType[$filename] = $obj; return $obj; } public static function getVideoTypeLabels($filename) { $obj = self::getVideoType($filename); $labels = ""; if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) { return 'Other'; } if ($obj->mp4) { $labels .= 'MP4'; } if ($obj->webm) { $labels .= 'Webm'; } if ($obj->m3u8) { $labels .= 'HLS'; } if ($obj->pdf) { $labels .= 'PDF'; } if ($obj->mp3) { $labels .= 'MP3'; } return $labels; } /** * Based on Roku Type * @param type $filename * @return string */ public static function getVideoTypeText($filename) { $obj = self::getVideoType($filename); $labels = ""; if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) { return __('Other'); } if ($obj->mp4) { return 'MP4'; } if ($obj->webm) { return 'WEBM'; } if ($obj->m3u8) { return 'HLS'; } if ($obj->pdf) { return 'PDF'; } if ($obj->mp3) { return 'MP3'; } return $labels; } public static function isPublic($videos_id) { // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { return true; } return false; } public static function userGroupAndVideoGroupMatch($users_id, $videos_id) { if (empty($videos_id)) { return false; } $ppv = AVideoPlugin::loadPluginIfEnabled("PayPerView"); if ($ppv) { $ppv->userCanWatchVideo($users_id, $videos_id); } // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { return true; } if (empty($users_id)) { return false; } $rowsUser = UserGroups::getUserGroups(User::getId()); if (empty($rowsUser)) { return false; } foreach ($rows as $value) { foreach ($rowsUser as $value2) { if ($value['id'] === $value2['id']) { return true; } } } return false; } public function getExternalOptions() { return $this->externalOptions; } public function setExternalOptions($externalOptions) { $this->externalOptions = $externalOptions; } public function setVideoStartSeconds($videoStartSeconds) { $externalOptions = json_decode($this->getExternalOptions()); $externalOptions->videoStartSeconds = $videoStartSeconds; $this->setExternalOptions(json_encode($externalOptions)); } public function getSerie_playlists_id() { return $this->serie_playlists_id; } public function setSerie_playlists_id($serie_playlists_id) { $this->serie_playlists_id = $serie_playlists_id; } public static function getVideoFromSeriePlayListsId($serie_playlists_id) { global $global, $config; $serie_playlists_id = intval($serie_playlists_id); $sql = "SELECT * FROM videos WHERE serie_playlists_id = '$serie_playlists_id' LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } /** * if will show likes, comments, share, etc * @return boolean */ public static function showYoutubeModeOptions() { global $video; if (!empty($_GET['evideo'])) { $v = self::decodeEvideo(); if (empty($v['video']['views_count'])) { return false; } else { return true; } } if (empty($video) || $video['type'] === 'notfound') { return false; } return true; } public static function decodeEvideo() { $evideo = false; if (!empty($_GET['evideo'])) { $evideo = json_decode(decryptString($_GET['evideo'])); } $video = array(); if (!empty($evideo)) { $video['id'] = 0; $video['type'] = 'embed'; $video['rotation'] = 0; $video['videoLink'] = $evideo->videoLink; $video['title'] = $evideo->title; $video['clean_title'] = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\] ]+/', '-', trim(strtolower(cleanString($evideo->title)))); if (empty($evideo->description) && !empty($evideo->videos_id)) { $divId = uniqid(); $video['description'] = '
'; } else { $video['description'] = @$evideo->description; } $video['duration'] = @$evideo->duration; $video['creator'] = @$evideo->creator; $video['likes'] = ""; $video['dislikes'] = ""; $video['category'] = "embed"; $video['views_count'] = intval(@$evideo->views_count); } return array('evideo' => $evideo, 'video' => $video); } private function getBlockedUsersIdsArray($users_id = 0) { if (empty($users_id)) { $users_id = intval(User::getId()); } if (empty($users_id)) { return array(); } if (!User::isLogged()) { return array(); } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return array(); } return ReportVideo::getAllReportedUsersIdFromUser($users_id); } public static function getIncludeType($video) { $vType = $video['type']; if ($vType == "linkVideo") { if (isHTMLPage($video['videoLink'])) { $vType = "embed"; } else { $vType = "video"; } } elseif ($vType == "live") { $vType = "../../plugin/Live/view/liveVideo"; } elseif ($vType == "linkAudio") { $vType = "audio"; } if (!in_array($vType, Video::$typeOptions)) { $vType = 'video'; } return $vType; } } } // just to convert permalink into clean_title if (!empty($_GET['v']) && empty($_GET['videoName'])) { $_GET['videoName'] = Video::get_clean_title($_GET['v']); } diff --git a/objects/videoAddViewCount.json.php b/objects/videoAddViewCount.json.php index 0cd760cd6..c98e481b1 100644 --- a/objects/videoAddViewCount.json.php +++ b/objects/videoAddViewCount.json.php @@ -1,56 +1,55 @@ getDuration()); if (!empty($seconds)) { $percent = (intval($_POST['currentTime']) / $seconds) * 100; $percentOptions = array(25,50,75,100); foreach ($percentOptions as $value) { if ($percent >= $value) { if (empty($_SESSION['addViewCount'][$_POST['id']][$value]) && !empty($_POST['currentTime'])) { if ($obj->addViewPercent($value)) { _session_start(); $_SESSION['addViewCount'][$_POST['id']][$value] = 1; } } } } -} +} if (empty($_SESSION['addViewCount'][$_POST['id']]['time'])) { $resp = $obj->addView(); _session_start(); $_SESSION['addViewCount'][$_POST['id']]['time'] = strtotime("+{$seconds} seconds"); -} else if (!empty($_POST['currentTime'])) { +} elseif (!empty($_POST['currentTime'])) { $resp = VideoStatistic::updateStatistic($obj->getId(), User::getId(), intval($_POST['currentTime'])); } else { $resp = 0; } $count = $obj->getViews_count(); $obj2 = new stdClass(); $obj2->status = !empty($resp); $obj2->count = $count; $obj2->resp = $resp; echo json_encode($obj2); diff --git a/objects/videoDelete.json.php b/objects/videoDelete.json.php index 9673eb07a..261397cc8 100644 --- a/objects/videoDelete.json.php +++ b/objects/videoDelete.json.php @@ -1,25 +1,25 @@ userCanManageVideo()) { $obj->msg = __("You can not Manage This Video"); die(json_encode($obj)); } $id = $obj->delete(); } echo '{"status":"'.$id.'"}'; diff --git a/objects/videoSuggest.php b/objects/videoSuggest.php index 0db73a614..87a8a25e0 100644 --- a/objects/videoSuggest.php +++ b/objects/videoSuggest.php @@ -1,22 +1,22 @@ -setIsSuggested($_POST['isSuggested']); - $id = $obj->save(); -} - -echo '{"status":"'.$id.'"}'; +setIsSuggested($_POST['isSuggested']); + $id = $obj->save(); +} + +echo '{"status":"'.$id.'"}'; diff --git a/objects/video_statistic.php b/objects/video_statistic.php index e41177e63..b5569ab1d 100644 --- a/objects/video_statistic.php +++ b/objects/video_statistic.php @@ -1,402 +1,428 @@ You need to update your system"; return false; } */ if (empty($videos_id)) { die(__("You need a video to generate statistics")); } $userId = empty($_SESSION["user"]["id"]) ? "NULL" : $_SESSION["user"]["id"]; $lastVideoTime = 0; if (empty($currentTime)) { $lastStatistic = self::getLastStatistics($videos_id, $userId); if (empty($currentTime) && !empty($lastStatistic)) { $lastVideoTime = intval($lastStatistic['lastVideoTime']); } } else { $lastVideoTime = intval($currentTime); } $sql = "INSERT INTO videos_statistics " . "(`when`,ip, users_id, videos_id, lastVideoTime, created, modified, session_id) values " . "(now(),?," . $userId . ",?,{$lastVideoTime},now(),now(),'" . session_id() . "')"; $insert_row = sqlDAL::writeSql($sql, "si", array(getRealIpAddr(), $videos_id)); if (!empty($global['mysqli']->insert_id)) { return $global['mysqli']->insert_id; } else { die($sql . ' Save Video Statistics Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } - static function updateStatistic($videos_id, $users_id, $lastVideoTime) { + public static function updateStatistic($videos_id, $users_id, $lastVideoTime) + { $lastStatistic = self::getLastStatistics($videos_id, $users_id); if (empty($lastStatistic)) { $vs = new VideoStatistic(0); $vs->setUsers_id($users_id); $vs->setVideos_id($videos_id); $vs->setWhen(date("Y-m-d h:i:s")); } else { $vs = new VideoStatistic($lastStatistic['id']); } $vs->setLastVideoTime($lastVideoTime); return $vs->save(); } - function save() { + public function save() + { $this->setSession_id(session_id()); if (empty($this->session_id) && empty($this->users_id)) { return false; } if (empty($this->users_id)) { $this->setUsers_id('null'); } return parent::save(); } - static function getLastStatistics($videos_id, $users_id = 0) { + public static function getLastStatistics($videos_id, $users_id = 0) + { if (!empty($users_id)) { $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND users_id = ? ORDER BY modified DESC LIMIT 1 "; $res = sqlDAL::readSql($sql, 'ii', array($videos_id, $users_id), true); } else { $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND session_id = ? ORDER BY modified DESC LIMIT 1 "; $res = sqlDAL::readSql($sql, 'is', array($videos_id, session_id()), true); } $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { return $result; } return false; } - static function getLastVideoTimeFromVideo($videos_id, $users_id) { + public static function getLastVideoTimeFromVideo($videos_id, $users_id) + { $row = self::getLastStatistics($videos_id, $users_id); if (empty($row)) { return 0; } return intval($row['lastVideoTime']); } - static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startDate = "", $endDate = "") { + public static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startDate = "", $endDate = "") + { global $global; if ($uniqueUsers) { $ast = "distinct(users_id)"; } else { $ast = "*"; } $sql = "SELECT count({$ast}) as total FROM videos_statistics WHERE 1=1 "; $formats = ""; $values = array(); if (!empty($videos_id)) { $sql .= " AND videos_id = ? "; $formats .= "i"; $values[] = $videos_id; } if (!empty($startDate)) { $sql .= " AND `when` >= ? "; $formats .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `when` <= ? "; $formats .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $formats, $values); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { //echo "
".$row['total']." --- ".$sql, "
"; return $result['total']; } return 0; } - static function getTotalLastDaysAsync($video_id, $numberOfDays) { + public static function getTotalLastDaysAsync($video_id, $numberOfDays) + { global $global, $advancedCustom; $md5 = ("{$video_id}_{$numberOfDays}"); $path = getCacheDir() . "getTotalLastDaysAsync/"; make_path($path); $cacheFileName = "{$path}{$md5}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } $total = static::getTotalLastDays($video_id, $numberOfDays); file_put_contents($cacheFileName, json_encode($total)); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 60) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalLastDaysAsync.php' '$video_id' '$numberOfDays' '$cacheFileName'"); _error_log("getTotalLastDaysAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } - static function getTotalLastDays($video_id, $numberOfDays, $returnArray = array()) { + public static function getTotalLastDays($video_id, $numberOfDays, $returnArray = array()) + { if ($numberOfDays < 0) { return $returnArray; } $date = date("Y-m-d", strtotime("-{$numberOfDays} days")); $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . " 00:00:00", $date . " 23:59:59"); $numberOfDays--; return static::getTotalLastDays($video_id, $numberOfDays, $returnArray); } - static function getTotalToday($video_id, $hour = 0, $returnArray = array()) { + public static function getTotalToday($video_id, $hour = 0, $returnArray = array()) + { if ($hour >= 24) { return $returnArray; } $date = date("Y-m-d {$hour}", time()); //echo $date;exit; $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . ":00:00", $date . ":59:59"); $hour++; return static::getTotalToday($video_id, $hour, $returnArray); } - static function getTotalTodayAsync($video_id) { + public static function getTotalTodayAsync($video_id) + { global $global, $advancedCustom; $cacheFileName = getCacheDir() . "getTotalTodayAsync_{$video_id}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } $total = static::getTotalToday($video_id); file_put_contents($cacheFileName, json_encode($total)); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 60) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalTodayAsync.php' '$video_id' '$cacheFileName'"); _error_log("getTotalTodayAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } - function getWhen() { + public function getWhen() + { return $this->when; } - function getIp() { + public function getIp() + { return $this->ip; } - function getUsers_id() { + public function getUsers_id() + { return $this->users_id; } - function getVideos_id() { + public function getVideos_id() + { return $this->videos_id; } - function getLastVideoTime() { + public function getLastVideoTime() + { return $this->lastVideoTime; } - function setWhen($when) { + public function setWhen($when) + { $this->when = $when; } - function setIp($ip) { + public function setIp($ip) + { $this->ip = $ip; } - function setUsers_id($users_id) { + public function setUsers_id($users_id) + { $this->users_id = intval($users_id); if (empty($this->users_id)) { $this->users_id = 'null'; } } - function setVideos_id($videos_id) { + public function setVideos_id($videos_id) + { $this->videos_id = intval($videos_id); } - function setLastVideoTime($lastVideoTime) { + public function setLastVideoTime($lastVideoTime) + { $this->lastVideoTime = intval($lastVideoTime); } - function getSession_id() { + public function getSession_id() + { return $this->session_id; } - function setSession_id($session_id) { + public function setSession_id($session_id) + { $this->session_id = $session_id; } - static function getChannelsWithMoreViews($daysLimit = 30) { + public static function getChannelsWithMoreViews($daysLimit = 30) + { global $global; // get unique videos ids from the requested timeframe $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $channels = array(); if ($res != false) { $channelsPerUser = array(); // get the channel owner from each of those videos foreach ($fullData as $row) { $users_id = Video::getOwner($row['videos_id']); if (empty($channelsPerUser[$users_id])) { $channelsPerUser[$users_id] = array(); } $channelsPerUser[$users_id][] = $row['videos_id']; } foreach ($channelsPerUser as $key => $value) { // count how many views each one has $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id IN (" . implode(",", $value) . ") AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { $channels[$key]['users_id'] = $key; $channels[$key]['total'] = intval($result2['total']); } } } // return more first - usort($channels, function($a, $b) { + usort($channels, function ($a, $b) { return $a['total'] - $b['total']; }); return $channels; } - static function getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly, $daysLimit = 30) { + public static function getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly, $daysLimit = 30) + { global $global; // get unique videos ids from the requested timeframe $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics s " . " LEFT JOIN videos v ON v.id = videos_id " . " WHERE DATE(s.created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $sql .= " AND v.users_id = '{$user['id']}' "; } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; } $sql .= static::getSqlLimit(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $channels = array(); $videos = array(); if ($res != false) { - foreach ($fullData as $key => $value) { // count how many views each one has $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id = {$value['videos_id']} AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; - + $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { - $video = Video::getVideo($value['videos_id'], $status, false, false, $suggestedOnly, $showUnlisted, false, $showOnlyLoggedUserVideos); - if(empty($video)){ + if (empty($video)) { continue; } $video['total'] = $result2['total']; $videos[] = $video; } } } // return more first - usort($videos, function($a, $b) { + usort($videos, function ($a, $b) { return $a['total'] - $b['total']; }); return $videos; } - static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) { + public static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) + { $channels = self::getChannelsWithMoreViews($daysLimit); $users_id = array(); foreach ($channels as $value) { $users_id[] = $value['users_id']; } return $users_id; } - static function getChannelsTotalViews($users_id, $daysLimit = 30) { + public static function getChannelsTotalViews($users_id, $daysLimit = 30) + { global $global; $users_id = intval($users_id); // count how many views each one has $sql2 = "SELECT count(s.id) as total FROM videos_statistics s " . " LEFT JOIN videos v ON v.id = videos_id WHERE v.users_id = $users_id " . " AND DATE(s.created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { return intval($result2['total']); } return 0; } - } diff --git a/objects/videos.json.php b/objects/videos.json.php index bf5b8f576..7f9948e50 100644 --- a/objects/videos.json.php +++ b/objects/videos.json.php @@ -1,63 +1,62 @@ $value) { unset($value['password']); unset($value['recoverPass']); $name = empty($value['name'])?$value['user']:$value['name']; //$categories[$key]['comment'] = "
{$name}
{$value['created']}
". nl2br($value['comment'])."
"; $videos[$key]['creator'] = '
User Photo
'.$name.'' . User::getEmailVerifiedIcon($value['users_id']) . ' '.humanTiming(strtotime($value['videoCreation'])).'
'; $videos[$key]['next_video'] = array(); $videos[$key]['description'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['description']); $videos[$key]['title'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['title']); $videos[$key]['clean_title'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['clean_title']); $videos[$key]['typeLabels'] = Video::getVideoTypeLabels($videos[$key]['filename']); $videos[$key]['maxResolution'] = Video::getHigestResolution($videos[$key]['filename']); - if(!empty($videos[$key]['next_videos_id'])){ + if (!empty($videos[$key]['next_videos_id'])) { unset($_POST['searchPhrase']); $videos[$key]['next_video'] = Video::getVideo($videos[$key]['next_videos_id']); } - if($videos[$key]['type']=='article'){ + if ($videos[$key]['type'] == 'article') { $videos[$key]['videosURL'] = getVideosURLArticle($videos[$key]['filename']); - }else if($videos[$key]['type']=='image'){ + } elseif ($videos[$key]['type'] == 'image') { $videos[$key]['videosURL'] = getVideosURLIMAGE($videos[$key]['filename']); - }else if($videos[$key]['type']=='zip'){ + } elseif ($videos[$key]['type'] == 'zip') { $videos[$key]['videosURL'] = getVideosURLZIP($videos[$key]['filename']); - }else - if($videos[$key]['type']=='pdf'){ + } elseif ($videos[$key]['type'] == 'pdf') { $videos[$key]['videosURL'] = getVideosURLPDF($videos[$key]['filename']); - }else if($videos[$key]['type']=='audio'){ + } elseif ($videos[$key]['type'] == 'audio') { $videos[$key]['videosURL'] = getVideosURLAudio($videos[$key]['filename']); - }else{ + } else { $videos[$key]['videosURL'] = getVideosURL($videos[$key]['filename']); } unset($videos[$key]['password']); unset($videos[$key]['recoverPass']); } echo '{ "current": '.$_REQUEST['current'].',"rowCount": '.$_REQUEST['rowCount'].', "total": '.$total.', "rows":'. json_encode($videos).'}'; diff --git a/plugin/Articles/updateDescriptions.php b/plugin/Articles/updateDescriptions.php index 1858d608b..f0cfb033c 100644 --- a/plugin/Articles/updateDescriptions.php +++ b/plugin/Articles/updateDescriptions.php @@ -1,25 +1,25 @@ setDescription(nl2br(textToLink($value['description']))); $video->save(); echo "{$value['title']}
"; } - + } diff --git a/plugin/Articles/updateDescriptionsRemoveTags.php b/plugin/Articles/updateDescriptionsRemoveTags.php index 727b9c88f..a7bfe99ac 100644 --- a/plugin/Articles/updateDescriptionsRemoveTags.php +++ b/plugin/Articles/updateDescriptionsRemoveTags.php @@ -1,35 +1,35 @@

"); - + if($newDescription==$value['description']){ continue; } $newDescription = br2nl($newDescription); if($newDescription==$value['description']){ continue; } if(empty($newDescription)){ continue; } - + $video = new Video("", "", $value['id']); $video->setDescription($newDescription); $video->save(); echo "{$value['title']}
"; - + } diff --git a/plugin/Meet/Meet.php b/plugin/Meet/Meet.php index 6ba97c4f2..9d24dce2c 100644 --- a/plugin/Meet/Meet.php +++ b/plugin/Meet/Meet.php @@ -1,570 +1,570 @@ secret = md5($global['systemRootPath'] . $global['salt'] . "meet"); $o = new stdClass(); $o->type = "textarea"; $o->value = "{UserName} is inviting you to a meeting. Topic: {topic} Join Meeting {meetLink} Passcode: {password} "; $obj->invitation = $o; $o = new stdClass(); $o->type = array('ca1.ypt.me' => "North America 1", 'eu1.ypt.me' => "Europe 1", 'custom' => "Custom Jitsi"); $o->value = 'ca1.ypt.me'; $obj->server = $o; $obj->CUSTOM_JITSI_DOMAIN = "jitsi.eu1.ypt.me"; $obj->JWT_APP_ID = "my_jitsi_app_id"; $obj->JWT_APP_SECRET = "my_jitsi_app_secret"; return $obj; } static function getTokenArray($meet_schedule_id, $users_id = 0) { global $config; $obj = AVideoPlugin::getDataObject("Meet"); if (empty($users_id)) { $users_id = User::getId(); } $m = new Meet_schedule($meet_schedule_id); $room = $m->getCleanName(); if (empty($users_id)) { $user = []; } else { $u = new User($users_id); $user = [ "avatar" => $u->getPhotoDB(), "name" => $u->getNameIdentificationBd(), "email" => $u->getEmail(), "id" => $users_id ]; } $jitsiPayload = [ "context" => [ "user" => $user, "group" => $config->getWebSiteTitle() ], "aud" => self::getAUD(), "iss" => self::getISS(), "sub" => "meet.jitsi", "room" => $room, "exp" => strtotime("+30 hours"), "moderator" => self::isModerator($meet_schedule_id) ]; return $jitsiPayload; // HS256 } static function getToken($meet_schedule_id, $users_id = 0) { $m = new Meet_schedule($meet_schedule_id); $jitsiPayload = self::getTokenArray($meet_schedule_id, $users_id); $key = self::getSecret(); //var_dump($jitsiPayload, $key); return JWT::encode($jitsiPayload, $key); // HS256 } static function getSecret() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_SECRET == 'my_jitsi_app_secret'){ return $obj->secret; }else{ return $obj->JWT_APP_SECRET; } } else { return $obj->secret; } } - + static function getAPPID() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_ID == 'my_jitsi_app_id'){ return "avideo"; }else{ return $obj->JWT_APP_ID; } } else { return "avideo"; } } - + static function getISS() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_ID == 'my_jitsi_app_id'){ return "*"; }else{ return $obj->JWT_APP_ID; } } else { return "*"; } } - + static function getAUD() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_ID == 'my_jitsi_app_id'){ return "avideo"; }else{ return $obj->JWT_APP_ID; } } else { return "avideo"; } } static function getMeetServer() { $obj = AVideoPlugin::getDataObject("Meet"); return "https://{$obj->server->value}/"; } public function getPluginMenu() { global $global; //return ' Edit'; return ' Check Servers'; } static function getMeetServerStatus($cache = 30) { global $global; $secret = self::getSecret(); $meetServer = self::getMeetServer(); if ($meetServer == "https://custom/") { $obj = AVideoPlugin::getDataObject("Meet"); $json = new stdClass(); $json->error = false; $json->url = $obj->CUSTOM_JITSI_DOMAIN; $json->isInstalled = true; $json->msg = $obj->CUSTOM_JITSI_DOMAIN; $json->host = "custom"; $json->jibrisInfo = new stdClass(); $json->jibrisInfo->jibris = array(); return $json; } $name = "getMeetServerStatus{$global['webSiteRootURL']}{$secret}{$meetServer}"; $json = new stdClass(); $json->content = ObjectYPT::getCache($name, $cache); if (!empty($json->content) && !empty($json->time)) { $json = json_decode($json->content); $json->msg = "From Cache"; } else { $url = $meetServer . "api/checkMeet.json.php?webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&secret=" . $secret; $content = url_get_contents($url); $json = json_decode($content); if (!empty($json)) { $json->time = time(); $json->url = $url; $json->content = $content; if (empty($json->error) && $json->isInstalled) { ObjectYPT::setCache($name, json_encode($json)); if (empty($json->msg)) { $json->msg = "Just create Cache"; } } else { if (empty($json->msg)) { $json->msg = "Error did not create Cache"; } } } else { $json = new stdClass(); $json->time = time(); $json->error = true; $json->msg = "Error we could not check your server"; } } $json->when = humanTimingAgo($json->time); return $json; } static function getDomain() { $json = self::getMeetServerStatus(); if (empty($json) || empty($json->host) || empty($json->isInstalled)) { return false; } if ($json->host == 'custom') { return "custom"; } $obj = AVideoPlugin::getDataObject("Meet"); return "{$json->host}.{$obj->server->value}"; } static function getDomainURL() { $meetDomain = self::getDomain(); if ($meetDomain == 'custom') { $obj = AVideoPlugin::getDataObject("Meet"); $domain = $obj->CUSTOM_JITSI_DOMAIN; } else { $domain = $meetDomain; } return $domain; } static function getJoinURL() { $domain = self::getDomainURL(); $url = "https://" . $domain . "/"; return $url; } static function getRoomID($meet_schedule_id) { $roomName = ""; $m = new Meet_schedule($meet_schedule_id); if (empty($m->getUsers_id())) { return $roomName; } if (!empty($meet_schedule_id)) { $roomName .= $m->getCleanName(); } $token = self::getToken($meet_schedule_id); $roomName .= "?jwt={$token}"; $obj = new stdClass(); if(class_exists("Live")){ $obj->getRTMPLink = Live::getRTMPLink($m->getUsers_id()); } $obj->shareLink = Meet::getMeetShortLink($meet_schedule_id); $roomName .= "&json=" . urlencode(json_encode($obj)); return $roomName; } static function isCustomJitsi() { $json = self::getMeetServerStatus(); if (empty($json) || empty($json->host) || empty($json->isInstalled)) { return true; } if ($json->host == 'custom') { return true; } return false; } static function validateRoomName($room) { return cleanURLName(ucwords($room)); } static function createRoomName($topic, $users_id = 0) { if (empty($users_id)) { if (User::isLogged()) { $identification = User::getNameIdentification(); } } else { $identification = User::getNameIdentificationById($users_id); } if (empty($identification)) { die("User could not be identified"); } $roomName = $identification . "-" . $topic; return self::validateRoomName($roomName); } public function getHTMLMenuRight() { global $global; if (!User::isLogged()) { return ""; } return '

  • '; } public static function getMeetLink($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } $ms = new Meet_schedule($meet_schedule_id); return $ms->getMeetLink(); } public static function getMeetShortLink($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } $ms = new Meet_schedule($meet_schedule_id); return $ms->getMeetShortLink(); } static function canManageSchedule($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } $meet = new Meet_schedule($meet_schedule_id); if ($meet->canManageSchedule()) { return true; } } static function canJoinMeet($meet_schedule_id) { $obj = self::canJoinMeetWithReason($meet_schedule_id); return $obj->canJoin; } static function canJoinMeetWithReason($meet_schedule_id) { $obj = new stdClass(); $obj->canJoin = false; $obj->reason = ""; if (User::isAdmin()) { $obj->canJoin = true; $obj->reason = "Is Admin"; return $obj; } $meet = new Meet_schedule($meet_schedule_id); if (User::getId() == $meet->getUsers_id()) { $obj->canJoin = true; $obj->reason = "Is the meet owner"; return $obj; } /** * Public = 2 * Logged Users Only = 1 * Specific User Groups = 0 * @return type */ if (empty($meet->getStarts()) || strtotime($meet->getStarts()) <= time()) { // means public if ($meet->getPublic() == "2") { $obj->canJoin = true; $obj->reason = "Is public"; return $obj; } else if ($meet->getPublic() == "1") { $obj->canJoin = User::isLogged(); $obj->reason = $obj->canJoin ? "Is logged" : "Must be logged to be able to join"; return $obj; } else { $obj->canJoin = self::userGroupMatch($meet_schedule_id, User::getId()); $obj->reason = $obj->canJoin ? "The user group match" : "Must be on the usergroup to be able to join"; return $obj; } } else { $obj->reason = "The meet does not start yet"; return $obj; } } static function isModerator($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } if (!User::isLogged()) { return false; } if (User::isAdmin()) { return true; } $meet = new Meet_schedule($meet_schedule_id); if (User::getId() == $meet->getUsers_id()) { return true; } return false; } static function getButtons($meet_schedule_id) { /* return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'embedmeeting', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'recording', 'livestreaming', 'etherpad', 'sharedvideo', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'invite', 'feedback', 'stats', 'shortcuts', 'tileview', 'videobackgroundblur', 'download', 'help', 'mute-everyone', 'security' ]; * */ if (self::isModerator($meet_schedule_id)) { if (self::hasJibris()) { return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'livestreaming', 'etherpad', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'feedback', 'stats', 'shortcuts', 'tileview', 'download', 'help', 'mute-everyone' ]; } else { return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'etherpad', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'feedback', 'stats', 'shortcuts', 'tileview', 'download', 'help', 'mute-everyone' ]; } } else { return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'etherpad', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'feedback', 'stats', 'shortcuts', 'tileview', 'download', 'help', 'mute-everyone' ]; } } static function hasJibris() { $serverStatus = Meet::getMeetServerStatus(); return count($serverStatus->jibrisInfo->jibris); } static function userGroupMatch($meet_schedule_id, $users_id) { global $global; if (User::isAdmin()) { return true; } if (User::isLogged()) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; $userGroups = UserGroups::getUserGroups(User::getId()); $meetGroups = Meet_schedule_has_users_groups::getAllFromSchedule($meet_schedule_id); foreach ($userGroups as $value) { foreach ($meetGroups as $value2) { if ($value['id'] == $value2['users_groups_id']) { return true; } } } } return false; } static function getServer() { $m = AVideoPlugin::loadPlugin("Meet"); $pObj = AVideoPlugin::getDataObject("Meet"); $obj = $m->getEmptyDataObject(); $obj->server->type = object_to_array($obj->server->type); return array("name" => $obj->server->type[$pObj->server->value], "domain" => $pObj->server->value); } static function createJitsiButton($title, $svg, $onclick, $class = "", $style = "", $id = "") { global $global; if (empty($id)) { $id = "avideoMeet" . uniqid(); } $svgContent = file_get_contents($global['systemRootPath'] . 'plugin/Meet/buttons/' . $svg); $btn = '
    ' . '' . '
    ' . '
    ' . $svgContent . '
    ' . '
    ' . '
    ' . ''; return $btn; } static function createJitsiRecordStartStopButton($rtmpLink, $dropURL) { $start = self::createJitsiButton(__("Go Live"), "startLive.svg", "aVideoMeetStartRecording('$rtmpLink','$dropURL');", "hideOnLive"); $stop = self::createJitsiButton(__("Stop Live"), "stopLive.svg", "aVideoMeetStopRecording('$rtmpLink','$dropURL');", "showOnLive", "display:none;"); return $start . $stop; } static function getInvitation($meet_schedule_id) { $objM = AVideoPlugin::getObjectDataIfEnabled("Meet"); $ms = new Meet_schedule($meet_schedule_id); $invitation = $objM->invitation->value; $topic = $ms->getTopic(); $pass = $ms->getPassword(); if (empty($topic)) { $invitation = preg_replace("/(\n|\r)[^\n\r]*{topic}[^\n\r]*(\n|\r)/i", "", $invitation); } else { $invitation = preg_replace("/{topic}/i", $topic, $invitation); } if (empty($pass)) { $invitation = preg_replace("/(\n|\r)[^\n\r]*{password}[^\n\r]*(\n|\r)/i", "", $invitation); } else { $invitation = preg_replace("/{password}/i", $pass, $invitation); } $invitation = preg_replace("/{UserName}/i", User::getNameIdentificationById($ms->getUsers_id()), $invitation); $invitation = preg_replace("/{meetLink}/i", $ms->getMeetLink(), $invitation); return $invitation; } static function validatePassword($meet_schedule_id, $password){ if(User::isAdmin() || self::isModerator($meet_schedule_id)){ return true; } $meet = new Meet_schedule($meet_schedule_id); if($meet->getPassword()){ if(empty($_SESSION['user']['meet_password'][$meet_schedule_id])){ if(!empty($password) && $meet->getPassword()==$password){ _session_start(); $_SESSION['user']['meet_password'][$meet_schedule_id] = 1; return true; }else{ return false; } } } return true; } } diff --git a/plugin/Meet/Objects/Meet_join_log.php b/plugin/Meet/Objects/Meet_join_log.php index 75320f4f0..998c86161 100644 --- a/plugin/Meet/Objects/Meet_join_log.php +++ b/plugin/Meet/Objects/Meet_join_log.php @@ -1,177 +1,174 @@ errno . ') ' . $global['mysqli']->error); } return $rows; } - - + static function getAllFromUser($users_id) { global $global; if (!static::isTableInstalled()) { _error_log("You need to install the meet plugin tables before use it", AVideoLog::$ERROR); return array(); } $users_id = intval($users_id); - + if(empty($users_id)){ return false; } $sql = "SELECT me.*, ml.* FROM " . static::getTableName() . " ml " . " LEFT JOIN meet_schedule me ON me.id = ml.meet_schedule_id " . "WHERE ml.users_id=$users_id "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - - + static function getSearchFieldsNames() { return array('ip', 'user_agent'); } static function getTableName() { return 'meet_join_log'; } static function getAllMeet_schedule() { global $global; $table = "meet_schedule"; $sql = "SELECT * FROM {$table} WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { _error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } static function getAllUsers() { global $global; $table = "users"; $sql = "SELECT * FROM {$table} WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { _error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } function setId($id) { $this->id = intval($id); } function setMeet_schedule_id($meet_schedule_id) { $this->meet_schedule_id = intval($meet_schedule_id); } function setUsers_id($users_id) { $this->users_id = intval($users_id); } function setIp($ip) { $this->ip = $ip; } function setUser_agent($user_agent) { $this->user_agent = $user_agent; } function getId() { return intval($this->id); } function getMeet_schedule_id() { return intval($this->meet_schedule_id); } function getUsers_id() { return intval($this->users_id); } function getIp() { return $this->ip; } function getUser_agent() { return $this->user_agent; } - + static function log($meet_schedule_id) { $log = new Meet_join_log(0); $log->setIp(getRealIpAddr()); $log->setMeet_schedule_id($meet_schedule_id); $log->setUser_agent((isMobile()?"Mobile: ":""). get_browser_name()); $log->setUsers_id(User::getId()); return $log->save(); } - + public function save() { - + if(empty($this->users_id)){ $this->users_id = 'NULL'; } - + return parent::save(); } - } diff --git a/plugin/Meet/Objects/Meet_schedule.php b/plugin/Meet/Objects/Meet_schedule.php index 73c887a22..9019b6ab6 100644 --- a/plugin/Meet/Objects/Meet_schedule.php +++ b/plugin/Meet/Objects/Meet_schedule.php @@ -1,377 +1,373 @@ errno . ') ' . $global['mysqli']->error); } return $rows; } - - + function setId($id) { $this->id = intval($id); - } - + } + function setUsers_id($users_id) { $this->users_id = intval($users_id); - } - + } + function setStatus($status) { $this->status = $status; - } - + } + /** * Public = 2 * Logged Users Only = 1 * Specific User Groups = 0 * @return type */ function setPublic($public) { $this->public = intval($public); - } - + } + function setLive_stream($live_stream) { $this->live_stream = intval($live_stream); - } - + } + function setPassword($password) { $this->password = $password; - } - + } + function setTopic($topic) { $this->topic = $topic; - } - + } + function setStarts($starts) { $this->starts = $starts; - } - + } + function setFinish($finish) { $this->finish = $finish; - } - + } + function setName($name) { $this->name = $name; - } - + } + function setMeet_code($meet_code) { $this->meet_code = $meet_code; - } - - + } + function getId() { return intval($this->id); - } - + } + function getUsers_id() { return intval($this->users_id); - } - + } + function getStatus() { return $this->status; - } - + } + /** * Public = 2 * Logged Users Only = 1 * Specific User Groups = 0 * @return type */ function getPublic() { return intval($this->public); - } - + } + function getLive_stream() { return intval($this->live_stream); - } - + } + function getPassword() { return $this->password; - } - + } + function getTopic() { return $this->topic; - } - + } + function getStarts() { return $this->starts; - } - + } + function getFinish() { return $this->finish; - } - + } + function getName() { return $this->name; - } - + } + function getCleanName(){ return cleanURLName($this->name); } - + function getMeet_code() { return $this->meet_code; - } + } public function getMeetLink() { global $global; return $global['webSiteRootURL'] . 'meet/'.$this->getId().'/' . urlencode($this->getName()); } public function getMeetShortLink() { global $global; return $global['webSiteRootURL'] . 'meet/'.$this->getId(); } - + static function getAllFromUsersId($users_id, $time="", $canAttend=false) { global $global; if (!static::isTableInstalled()) { return false; } - + $users_id = intval($users_id); if(empty($users_id)){ return false; } $sql = "SELECT * FROM " . static::getTableName() . " ms WHERE users_id = $users_id "; - + if($canAttend){ $userGroups = UserGroups::getUserGroups($users_id); $userGroupsIds = array(); foreach ($userGroups as $value){ $userGroupsIds[] = $value['id']; } - $sql .= " OR (public = 2 OR public = 1 "; + $sql .= " OR (public = 2 OR public = 1 "; if(!empty($userGroupsIds)){ - $sql .= " OR (public = 0 AND (SELECT count(id) FROM meet_schedule_has_users_groups WHERE meet_schedule_id=ms.id AND users_groups_id IN (". implode(",", $userGroupsIds)."))>0) "; + $sql .= " OR (public = 0 AND (SELECT count(id) FROM meet_schedule_has_users_groups WHERE meet_schedule_id=ms.id AND users_groups_id IN (". implode(",", $userGroupsIds)."))>0) "; } - $sql .= " ) "; + $sql .= " ) "; } $identification = User::getNameIdentificationById($users_id); if(!empty($time)){ unset($_POST['sort']); if($time=="today"){ - $sql .= " AND date(starts) = CURDATE() "; + $sql .= " AND date(starts) = CURDATE() "; $_POST['sort']['starts']="ASC"; - $sql .= self::getSqlFromPost(); + $sql .= self::getSqlFromPost(); }else if($time=="upcoming"){ $sql .= " AND date(starts) > CURDATE() "; $_POST['sort']['starts']="ASC"; - $sql .= self::getSqlFromPost(); + $sql .= self::getSqlFromPost(); }else if($time=="past"){ - $sql .= " AND date(starts) < CURDATE() "; + $sql .= " AND date(starts) < CURDATE() "; $_POST['sort']['starts']="DESC"; $sql .= self::getSqlFromPost(); } unset($_POST['sort']); }else{ $sql .= self::getSqlFromPost(); } $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); unset($_GET['order']); if ($res != false) { foreach ($fullData as $row) { $row['identification'] = $identification; $row['link'] = Meet::getMeetLink($row['id']); if(empty($row['public'])){ $row['userGroups'] = Meet_schedule_has_users_groups::getAllFromSchedule($row['id']); }else{ $row['userGroups'] = array(); } $row['invitation'] = Meet::getInvitation($row['id']); $row['joinURL'] = ""; if(Meet::canJoinMeet($row['id'])){ $row['joinURL'] = Meet::getJoinURL(); $row['roomID'] = Meet::getRoomID($row['id']); } $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - - + static function getTotalFromUsersId($users_id, $time="", $canAttend=false) { //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; if (!static::isTableInstalled()) { return 0; } $users_id = intval($users_id); if(empty($users_id)){ return false; } $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; - + if($canAttend){ $userGroups = UserGroups::getUserGroups($users_id); $userGroupsIds = array(); foreach ($userGroups as $value){ $userGroupsIds[] = $value['id']; } - $sql .= " OR (public = 2 OR public = 1 "; + $sql .= " OR (public = 2 OR public = 1 "; if(!empty($userGroupsIds)){ - $sql .= " OR (public = 0 AND (SELECT count(id) FROM meet_schedule_has_users_groups WHERE meet_schedule_id=ms.id AND users_groups_id IN (". implode(",", $userGroupsIds)."))>0) "; + $sql .= " OR (public = 0 AND (SELECT count(id) FROM meet_schedule_has_users_groups WHERE meet_schedule_id=ms.id AND users_groups_id IN (". implode(",", $userGroupsIds)."))>0) "; } - $sql .= " ) "; + $sql .= " ) "; } if(!empty($time)){ unset($_POST['sort']); if($time=="today"){ - $sql .= " AND date(starts) = CURDATE() "; - $sql .= " ORDER BY starts ASC "; + $sql .= " AND date(starts) = CURDATE() "; + $sql .= " ORDER BY starts ASC "; }else if($time=="upcoming"){ - $sql .= " AND date(starts) > CURDATE() "; - $sql .= " ORDER BY starts ASC "; + $sql .= " AND date(starts) > CURDATE() "; + $sql .= " ORDER BY starts ASC "; }else if($time=="past"){ - $sql .= " AND date(starts) < CURDATE() "; - $sql .= " ORDER BY starts DESC "; + $sql .= " AND date(starts) < CURDATE() "; + $sql .= " ORDER BY starts DESC "; } } $sql .= self::getSqlSearchFromPost(); $res = sqlDAL::readSql($sql); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); return $countRow; } - - + static function getAll($time="") { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; if(!empty($time)){ unset($_POST['sort']); if($time=="today"){ - $sql .= " AND date(starts) = CURDATE() "; + $sql .= " AND date(starts) = CURDATE() "; $_POST['sort']['starts']="ASC"; - $sql .= self::getSqlFromPost(); + $sql .= self::getSqlFromPost(); }else if($time=="upcoming"){ $sql .= " AND date(starts) > CURDATE() "; $_POST['sort']['starts']="ASC"; - $sql .= self::getSqlFromPost(); + $sql .= self::getSqlFromPost(); }else if($time=="past"){ - $sql .= " AND date(starts) < CURDATE() "; + $sql .= " AND date(starts) < CURDATE() "; $_POST['sort']['starts']="DESC"; $sql .= self::getSqlFromPost(); } unset($_POST['sort']); }else{ $sql .= self::getSqlFromPost(); } $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); unset($_GET['order']); if ($res != false) { foreach ($fullData as $row) { $row['link'] = Meet::getMeetLink($row['id']); $row['identification'] = User::getNameIdentificationById($row['users_id']); if(empty($row['public'])){ $row['userGroups'] = Meet_schedule_has_users_groups::getAllFromSchedule($row['id']); }else{ $row['userGroups'] = array(); } - + $row['isModerator'] = Meet::isModerator($row['id']); $row['invitation'] = Meet::getInvitation($row['id']); $row['joinURL'] = ""; if(Meet::canJoinMeet($row['id'])){ $row['joinURL'] = Meet::getJoinURL(); $row['roomID'] = Meet::getRoomID($row['id']); } $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - + static function getTotal($time="") { //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; if (!static::isTableInstalled()) { return 0; } $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; if(!empty($time)){ unset($_POST['sort']); if($time=="today"){ - $sql .= " AND date(starts) = CURDATE() "; - $sql .= " ORDER BY starts ASC "; + $sql .= " AND date(starts) = CURDATE() "; + $sql .= " ORDER BY starts ASC "; }else if($time=="upcoming"){ - $sql .= " AND date(starts) > CURDATE() "; - $sql .= " ORDER BY starts ASC "; + $sql .= " AND date(starts) > CURDATE() "; + $sql .= " ORDER BY starts ASC "; }else if($time=="past"){ - $sql .= " AND date(starts) < CURDATE() "; - $sql .= " ORDER BY starts DESC "; + $sql .= " AND date(starts) < CURDATE() "; + $sql .= " ORDER BY starts DESC "; } } $sql .= self::getSqlSearchFromPost(); $res = sqlDAL::readSql($sql); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); return $countRow; } - + function canManageSchedule(){ if(User::isAdmin()){ return true; } if(empty($this->getUsers_id())){ return false; } if($this->getUsers_id()==User::getId()){ return true; } return false; } - + function save() { if(empty($this->finish)){ $this->finish = 'null'; } return parent::save(); } - + } diff --git a/plugin/Meet/Objects/Meet_schedule_has_users_groups.php b/plugin/Meet/Objects/Meet_schedule_has_users_groups.php index 0225c9f57..f32f1e799 100644 --- a/plugin/Meet/Objects/Meet_schedule_has_users_groups.php +++ b/plugin/Meet/Objects/Meet_schedule_has_users_groups.php @@ -1,137 +1,137 @@ errno . ') ' . $global['mysqli']->error); } return $rows; } static function getAllMeet_schedule() { global $global; $table = "meet_schedule"; $sql = "SELECT * FROM {$table} WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { _error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } static function getAllUsers_groups() { global $global; $table = "users_groups"; $sql = "SELECT * FROM {$table} WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { _error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } function setId($id) { $this->id = intval($id); } function setMeet_schedule_id($meet_schedule_id) { $this->meet_schedule_id = intval($meet_schedule_id); } function setUsers_groups_id($users_groups_id) { $this->users_groups_id = intval($users_groups_id); } function getId() { return intval($this->id); } function getMeet_schedule_id() { return intval($this->meet_schedule_id); } function getUsers_groups_id() { return intval($this->users_groups_id); } - + static function saveUsergroupsToMeet($meet_schedule_id, $user_groups_ids){ self::deleteAllFromMeet($meet_schedule_id); if(!is_array($user_groups_ids)){ return false; } foreach ($user_groups_ids as $value) { $ms = new Meet_schedule_has_users_groups(0); $ms->setUsers_groups_id($value); $ms->setMeet_schedule_id($meet_schedule_id); $ms->save(); } return true; } - + static function deleteAllFromMeet($meet_schedule_id) { global $global; if (!empty($meet_schedule_id)) { $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE meet_schedule_id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($meet_schedule_id)); } _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); return false; } } diff --git a/plugin/Meet/View/Meet_join_log/add.json.php b/plugin/Meet/View/Meet_join_log/add.json.php index 47e020462..fefd84ae5 100644 --- a/plugin/Meet/View/Meet_join_log/add.json.php +++ b/plugin/Meet/View/Meet_join_log/add.json.php @@ -1,27 +1,27 @@ error = true; $obj->msg = ""; $plugin = AVideoPlugin::loadPluginIfEnabled('Meet'); - + if(!User::isAdmin()){ $obj->msg = "You cant do this"; die(json_encode($obj)); } $o = new Meet_join_log(@$_POST['id']); $o->setMeet_schedule_id($_POST['meet_schedule_id']); $o->setUsers_id($_POST['users_id']); $o->setIp($_POST['ip']); $o->setUser_agent($_POST['user_agent']); if($id = $o->save()){ $obj->error = false; } echo json_encode($obj); diff --git a/plugin/Meet/View/Meet_join_log/index_body.php b/plugin/Meet/View/Meet_join_log/index_body.php index ca43650f3..cc56d677f 100644 --- a/plugin/Meet/View/Meet_join_log/index_body.php +++ b/plugin/Meet/View/Meet_join_log/index_body.php @@ -1,214 +1,213 @@ -
    " required="true">
    " required="true">
    #
    #
    -